mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-12-01 09:26:47 +00:00
Compare commits
84
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a3c712f8d3 | ||
|
|
56f25f5a39 | ||
|
|
68b3e9a07c | ||
|
|
5190b197e8 | ||
|
|
09c18205d4 | ||
|
|
ea1e4f02d0 | ||
|
|
b5e490b987 | ||
|
|
7b8141d174 | ||
|
|
83ebd994c7 | ||
|
|
c4a48dd1e6 | ||
|
|
5bb7edcade | ||
|
|
75948dc617 | ||
|
|
0edfcab8dd | ||
|
|
95843529ba | ||
|
|
3930b1841e | ||
|
|
070aa5f0cd | ||
|
|
0d42f37a5c | ||
|
|
837065bfbd | ||
|
|
2f9ec6936f | ||
|
|
fb455bf1db | ||
|
|
d2cbdd4609 | ||
|
|
844e103c86 | ||
|
|
2500e85c01 | ||
|
|
971d9d64a8 | ||
|
|
cfac798f9e | ||
|
|
34e8e04793 | ||
|
|
0664c04074 | ||
|
|
e454b29c6a | ||
|
|
4a8313eb67 | ||
|
|
fa145d7889 | ||
|
|
edcc61d4ba | ||
|
|
34c7106e7e | ||
|
|
ee409af54a | ||
|
|
04c4d993a6 | ||
|
|
0ee06d83b7 | ||
|
|
f9d3cd8d82 | ||
|
|
771c98fd92 | ||
|
|
82d9107865 | ||
|
|
f2b0264fac | ||
|
|
132611f159 | ||
|
|
a741edd80f | ||
|
|
8c3dd7aa48 | ||
|
|
b0792dd0a7 | ||
|
|
d9d6560b47 | ||
|
|
8cc0948a34 | ||
|
|
575280da74 | ||
|
|
46bfc12869 | ||
|
|
73ec57e911 | ||
|
|
fb84066f09 | ||
|
|
4d24c814cc | ||
|
|
9dc807a255 | ||
|
|
5d59538924 | ||
|
|
04c102e51f | ||
|
|
71bc23ed02 | ||
|
|
7c26965ece | ||
|
|
5c3a82c257 | ||
|
|
5fedb48b55 | ||
|
|
69d9fc12ca | ||
|
|
81f2499889 | ||
|
|
82a3bba7ec | ||
|
|
ee09d6b334 | ||
|
|
dc215cab54 | ||
|
|
99bbbbe1ac | ||
|
|
38121bcbfa | ||
|
|
5e7a50a36d | ||
|
|
17531c5927 | ||
|
|
e7df1aeb5b | ||
|
|
dc8e03bd40 | ||
|
|
4578150e5a | ||
|
|
bd97e70a56 | ||
|
|
206f114b34 | ||
|
|
2dc4db3918 | ||
|
|
98dc758bb7 | ||
|
|
b4c594c657 | ||
|
|
b55afdd704 | ||
|
|
136cddf6e2 | ||
|
|
b7d455ed11 | ||
|
|
ac23b8e79e | ||
|
|
af2d276f37 | ||
|
|
8154bb1047 | ||
|
|
b647853983 | ||
|
|
3350922456 | ||
|
|
69af979bfa | ||
|
|
a142916fef |
No files matched your search
+1
-1
@@ -1 +1 @@
|
||||
temurin-24
|
||||
temurin-25
|
||||
+2
-2
@@ -14,7 +14,7 @@
|
||||
# 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.9.11/apache-maven-3.9.11-bin.zip
|
||||
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.14/apache-maven-3.9.14-bin.zip
|
||||
wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.3.4/maven-wrapper-3.3.4.jar
|
||||
distributionSha256Sum=0d7125e8c91097b36edb990ea5934e6c68b4440eef4ea96510a0f6815e7eeadb
|
||||
distributionSha256Sum=55fadd669532a3205d5db95f490bf13971d8b0843526f407f29db0e61f074ab3
|
||||
wrapperSha256Sum=4e2fbf6554bc8a4702cdfdd3bef464f423393d784ddbb037216320ce55d5e4e1
|
||||
@@ -14,7 +14,6 @@ import java.nio.charset.StandardCharsets;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
@@ -130,7 +129,7 @@ public class TestUser {
|
||||
|
||||
public AccountAttributes accountAttributes() {
|
||||
return new AccountAttributes(true, registrationId, pniRegistrationId, "".getBytes(StandardCharsets.UTF_8), "", true,
|
||||
DeviceCapability.CAPABILITIES_REQUIRED_FOR_REGISTRATION)
|
||||
DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES)
|
||||
.withUnidentifiedAccessKey(unidentifiedAccessKey)
|
||||
.withRecoveryPassword(registrationPassword);
|
||||
}
|
||||
|
||||
@@ -45,8 +45,8 @@
|
||||
</modules>
|
||||
|
||||
<properties>
|
||||
<aws.sdk2.version>2.41.11</aws.sdk2.version>
|
||||
<braintree.version>3.47.0</braintree.version>
|
||||
<aws.sdk2.version>2.42.27</aws.sdk2.version>
|
||||
<braintree.version>3.48.0</braintree.version>
|
||||
<commons-csv.version>1.14.1</commons-csv.version>
|
||||
<commons-io.version>2.21.0</commons-io.version>
|
||||
<dropwizard.version>4.0.16</dropwizard.version>
|
||||
@@ -57,47 +57,47 @@
|
||||
<foundationdb.version>7.3.62</foundationdb.version>
|
||||
<foundationdb.api-version>730</foundationdb.api-version>
|
||||
<foundationdb.client-library-sha256>bfed237b787fae3cde1222676e6bfbb0d218fc27bf9e903397a7a7aa96fb2d33</foundationdb.client-library-sha256>
|
||||
<google-cloud-libraries.version>26.74.0</google-cloud-libraries.version>
|
||||
<grpc.version>1.73.0</grpc.version> <!-- should be kept in sync with the value from Google libraries-bom -->
|
||||
<google-cloud-libraries.version>26.79.0</google-cloud-libraries.version>
|
||||
<grpc.version>1.76.3</grpc.version> <!-- should be kept in sync with the value from Google libraries-bom -->
|
||||
<gson.version>2.13.2</gson.version>
|
||||
<guava.version>33.5.0-jre</guava.version>
|
||||
<!-- several libraries (AWS, Google Cloud) use Apache http components transitively, and we need to align them -->
|
||||
<httpcore.version>4.4.16</httpcore.version>
|
||||
<httpclient.version>4.5.14</httpclient.version>
|
||||
<jackson.version>2.21.0</jackson.version>
|
||||
<jackson.version>2.21.2</jackson.version>
|
||||
<junit-pioneer.version>2.3.0</junit-pioneer.version>
|
||||
<jsr305.version>3.0.2</jsr305.version>
|
||||
<kotlin.version>2.3.0</kotlin.version>
|
||||
<logback.version>1.5.25</logback.version>
|
||||
<logback-access-common.version>2.0.6</logback-access-common.version>
|
||||
<lettuce.version>6.8.1.RELEASE</lettuce.version>
|
||||
<libphonenumber.version>9.0.13</libphonenumber.version>
|
||||
<kotlin.version>2.3.20</kotlin.version>
|
||||
<logback.version>1.5.32</logback.version>
|
||||
<logback-access-common.version>2.0.12</logback-access-common.version>
|
||||
<lettuce.version>6.8.2.RELEASE</lettuce.version>
|
||||
<libphonenumber.version>9.0.21</libphonenumber.version>
|
||||
<logstash.logback.version>8.1</logstash.logback.version>
|
||||
<log4j-bom.version>2.25.3</log4j-bom.version>
|
||||
<log4j-bom.version>2.25.4</log4j-bom.version>
|
||||
<luajava.version>3.5.0</luajava.version>
|
||||
<micrometer.version>1.16.2</micrometer.version>
|
||||
<micrometer.version>1.16.4</micrometer.version>
|
||||
<netty.version>4.1.127.Final</netty.version>
|
||||
<!-- Must be less than or equal to the value from Google libraries-bom which controls the protobuf runtime version.
|
||||
See https://protobuf.dev/support/cross-version-runtime-guarantee/. -->
|
||||
<protoc.version>4.29.4</protoc.version>
|
||||
<protoc.version>4.33.2</protoc.version>
|
||||
<pushy.version>0.15.4</pushy.version>
|
||||
<reactor-bom.version>2025.0.2</reactor-bom.version> <!-- 3.8.2, see https://github.com/reactor/reactor#bom-versioning-scheme -->
|
||||
<resilience4j.version>2.3.0</resilience4j.version>
|
||||
<reactor-bom.version>2025.0.4</reactor-bom.version> <!-- 3.8.4, see https://github.com/reactor/reactor#bom-versioning-scheme -->
|
||||
<resilience4j.version>2.4.0</resilience4j.version>
|
||||
<semver4j.version>3.1.0</semver4j.version>
|
||||
<simple-grpc.version>0.2.0</simple-grpc.version>
|
||||
<slf4j.version>2.0.17</slf4j.version>
|
||||
<stripe.version>31.2.0</stripe.version>
|
||||
<swagger.version>2.2.42</swagger.version>
|
||||
<testcontainers.version>2.0.3</testcontainers.version>
|
||||
<swagger.version>2.2.46</swagger.version>
|
||||
<testcontainers.version>2.0.4</testcontainers.version>
|
||||
|
||||
<!-- images to use in tests via testcontainers -->
|
||||
<dynamodb.image>amazon/dynamodb-local:3.0.0@sha256:2fed5e3a965a4ba5aa6ac82baec57058b5a3848e959d705518f3fd579a77e76b</dynamodb.image>
|
||||
<localstack.image>localstack/localstack:4@sha256:5a97e0f9917a3f0d9630bb13b9d8ccf10cbe52f33252807d3b4e21418cc21348</localstack.image>
|
||||
<dynamodb.image>amazon/dynamodb-local:3.3.0@sha256:d89f8fcc6b1a39cb35976c248ed42a28c66ae00dc043099210f5571e42648ab4</dynamodb.image>
|
||||
<localstack.image>localstack/localstack:4.13@sha256:46302bcb91a7e8008e6394be8afafdbfa40fb77a54d4046a38be35992042d5de</localstack.image>
|
||||
<redis.image>redis:7.4-alpine@sha256:af1d0fc3f63b02b13ff7906c9baf7c5b390b8881ca08119cd570677fe2f60b55</redis.image>
|
||||
<redis-cluster.image>docker.io/bitnamilegacy/redis-cluster:7.4.3@sha256:a53d023fdfaf8a8d7ddc58da040d3494e4cb45772644618ffa44c42dcd32b9af</redis-cluster.image>
|
||||
|
||||
<!-- eclipse-temurin:24.0.2_12-jre-noble (note: always use the multi-arch manifest *LIST* here) -->
|
||||
<docker.image.sha256>85ecfc9bbb42af046d2bacbf1219d2005be4840cbfa16c2e6fd910d9ccfec95b</docker.image.sha256>
|
||||
<!-- eclipse-temurin:25.0.2_10-jre-noble (note: always use the multi-arch manifest *LIST* here) -->
|
||||
<docker.image.sha256>d2975fcad8dc9ac2180c0c278c8ae7b3443d36cb80845cb0811c20d9463f5fee</docker.image.sha256>
|
||||
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
</properties>
|
||||
@@ -167,14 +167,14 @@
|
||||
<dependency>
|
||||
<groupId>io.opentelemetry</groupId>
|
||||
<artifactId>opentelemetry-bom</artifactId>
|
||||
<version>1.54.0</version>
|
||||
<version>1.60.1</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.opentelemetry.instrumentation</groupId>
|
||||
<artifactId>opentelemetry-instrumentation-bom</artifactId>
|
||||
<version>2.20.0</version>
|
||||
<version>2.26.1</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
@@ -251,12 +251,12 @@
|
||||
<dependency>
|
||||
<groupId>commons-logging</groupId>
|
||||
<artifactId>commons-logging</artifactId>
|
||||
<version>1.3.5</version>
|
||||
<version>1.3.6</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.ow2.asm</groupId>
|
||||
<artifactId>asm</artifactId>
|
||||
<version>9.8</version>
|
||||
<version>9.9.1</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
@@ -370,6 +370,11 @@
|
||||
<artifactId>mockito-core</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.mockito</groupId>
|
||||
<artifactId>mockito-junit-jupiter</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
@@ -417,7 +422,7 @@
|
||||
<extension>
|
||||
<groupId>kr.motd.maven</groupId>
|
||||
<artifactId>os-maven-plugin</artifactId>
|
||||
<version>1.7.0</version>
|
||||
<version>1.7.1</version>
|
||||
</extension>
|
||||
</extensions>
|
||||
<pluginManagement>
|
||||
@@ -425,27 +430,27 @@
|
||||
<plugin>
|
||||
<groupId>com.google.cloud.tools</groupId>
|
||||
<artifactId>jib-maven-plugin</artifactId>
|
||||
<version>3.4.4</version>
|
||||
<version>3.4.6</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>3.5.2</version>
|
||||
<version>3.5.5</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-failsafe-plugin</artifactId>
|
||||
<version>3.5.2</version>
|
||||
<version>3.5.4</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-jar-plugin</artifactId>
|
||||
<version>3.4.2</version>
|
||||
<version>3.5.0</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-shade-plugin</artifactId>
|
||||
<version>3.6.0</version>
|
||||
<version>3.6.1</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
@@ -455,7 +460,7 @@
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>exec-maven-plugin</artifactId>
|
||||
<version>3.1.0</version>
|
||||
<version>3.6.3</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
@@ -501,16 +506,16 @@
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.13.0</version>
|
||||
<version>3.15.0</version>
|
||||
<configuration>
|
||||
<release>24</release>
|
||||
<release>25</release>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-jar-plugin</artifactId>
|
||||
<version>3.4.2</version>
|
||||
<version>3.5.0</version>
|
||||
<configuration>
|
||||
<archive>
|
||||
<manifest>
|
||||
@@ -523,7 +528,7 @@
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-dependency-plugin</artifactId>
|
||||
<version>3.8.1</version>
|
||||
<version>3.10.0</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<!--
|
||||
@@ -543,7 +548,7 @@
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-enforcer-plugin</artifactId>
|
||||
<version>3.5.0</version>
|
||||
<version>3.6.2</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
@@ -564,7 +569,7 @@
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-install-plugin</artifactId>
|
||||
<version>3.1.3</version>
|
||||
<version>3.1.4</version>
|
||||
<configuration>
|
||||
<skip>true</skip>
|
||||
</configuration>
|
||||
@@ -573,7 +578,7 @@
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-deploy-plugin</artifactId>
|
||||
<version>3.1.3</version>
|
||||
<version>3.1.4</version>
|
||||
<configuration>
|
||||
<skip>true</skip>
|
||||
</configuration>
|
||||
|
||||
@@ -231,10 +231,12 @@ messageCache: # Redis server configuration for message store cache
|
||||
cluster:
|
||||
configurationUri: redis://redis.example.com:6379/
|
||||
|
||||
attachments:
|
||||
maxUploadSizeInBytes: 1024
|
||||
|
||||
gcpAttachments: # GCP Storage configuration
|
||||
domain: example.com
|
||||
email: user@example.cocm
|
||||
maxSizeInBytes: 1024
|
||||
pathPrefix:
|
||||
rsaSigningKey: secret://gcpAttachments.rsaSigningKey
|
||||
|
||||
|
||||
+1
-1
@@ -555,7 +555,7 @@
|
||||
<dependency>
|
||||
<groupId>com.squareup.okio</groupId>
|
||||
<artifactId>okio-jvm</artifactId>
|
||||
<version>3.15.0</version>
|
||||
<version>3.16.4</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
+11
@@ -18,6 +18,7 @@ import org.whispersystems.textsecuregcm.attachments.TusConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.ApnConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.AppleAppStoreConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.AppleDeviceCheckConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.AttachmentsConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.AwsCredentialsProviderFactory;
|
||||
import org.whispersystems.textsecuregcm.configuration.BadgesConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.BraintreeConfiguration;
|
||||
@@ -122,6 +123,11 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
@JsonProperty
|
||||
private DynamoDbTables dynamoDbTables;
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
@JsonProperty
|
||||
private AttachmentsConfiguration attachments;
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
@JsonProperty
|
||||
@@ -412,6 +418,10 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
return webSocket;
|
||||
}
|
||||
|
||||
public AttachmentsConfiguration getAttachments() {
|
||||
return attachments;
|
||||
}
|
||||
|
||||
public GcpAttachmentsConfiguration getGcpAttachmentsConfiguration() {
|
||||
return gcpAttachments;
|
||||
}
|
||||
@@ -610,4 +620,5 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
public HlrLookupConfiguration getHlrLookupConfiguration() {
|
||||
return hlrLookup;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -142,6 +142,7 @@ import org.whispersystems.textsecuregcm.filters.RestDeprecationFilter;
|
||||
import org.whispersystems.textsecuregcm.filters.TimestampResponseFilter;
|
||||
import org.whispersystems.textsecuregcm.grpc.AccountsAnonymousGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.AccountsGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.AttachmentsGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.BackupsAnonymousGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.BackupsGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.CallQualitySurveyGrpcService;
|
||||
@@ -753,8 +754,9 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
cloudflareTurnHttpExecutor,
|
||||
config.getTurnConfiguration().cloudflare().retryConfigurationName(),
|
||||
cloudflareTurnRetryExecutor,
|
||||
cloudflareDnsResolver
|
||||
);
|
||||
cloudflareDnsResolver,
|
||||
dynamicConfigurationManager,
|
||||
experimentEnrollmentManager);
|
||||
|
||||
final CardinalityEstimator messageByteLimitCardinalityEstimator = new CardinalityEstimator(
|
||||
rateLimitersCluster,
|
||||
@@ -821,7 +823,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
final GcsAttachmentGenerator gcsAttachmentGenerator = new GcsAttachmentGenerator(
|
||||
config.getGcpAttachmentsConfiguration().domain(),
|
||||
config.getGcpAttachmentsConfiguration().email(),
|
||||
config.getGcpAttachmentsConfiguration().maxSizeInBytes(),
|
||||
config.getGcpAttachmentsConfiguration().pathPrefix(),
|
||||
config.getGcpAttachmentsConfiguration().rsaSigningKey().value());
|
||||
|
||||
@@ -946,7 +947,9 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
log.info("Registered spam filter: {}", filter.getClass().getName());
|
||||
});
|
||||
|
||||
final RemoteDeprecationFilter remoteDeprecationFilter = new RemoteDeprecationFilter(dynamicConfigurationManager);
|
||||
final RemoteDeprecationFilter remoteDeprecationFilter =
|
||||
new RemoteDeprecationFilter(accountsManager, accountAuthenticator, dynamicConfigurationManager);
|
||||
|
||||
final MetricServerInterceptor metricServerInterceptor = new MetricServerInterceptor(Metrics.globalRegistry, clientReleaseManager);
|
||||
|
||||
final ErrorMappingInterceptor errorMappingInterceptor = new ErrorMappingInterceptor();
|
||||
@@ -969,7 +972,9 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
new KeysGrpcService(accountsManager, keysManager, rateLimiters),
|
||||
new MessagesGrpcService(accountsManager, rateLimiters, messageSender, messageByteLimitCardinalityEstimator, spamChecker, Clock.systemUTC()),
|
||||
new BackupsGrpcService(accountsManager, backupAuthManager, backupMetrics),
|
||||
new DevicesGrpcService(accountsManager))
|
||||
new DevicesGrpcService(accountsManager),
|
||||
new AttachmentsGrpcService(experimentEnrollmentManager, rateLimiters,
|
||||
gcsAttachmentGenerator, tusAttachmentGenerator, config.getAttachments().maxUploadSizeInBytes()))
|
||||
.map(bindableService -> ServerInterceptors.intercept(bindableService,
|
||||
// Note: interceptors run in the reverse order they are added; the remote deprecation filter
|
||||
// depends on the user-agent context so it has to come first here!
|
||||
@@ -988,7 +993,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
new KeysAnonymousGrpcService(accountsManager, keysManager, zkSecretParams, Clock.systemUTC()),
|
||||
new PaymentsGrpcService(currencyManager),
|
||||
new MessagesAnonymousGrpcService(accountsManager, rateLimiters, messageSender, groupSendTokenUtil, messageByteLimitCardinalityEstimator, spamChecker, Clock.systemUTC()),
|
||||
new BackupsAnonymousGrpcService(backupManager, backupMetrics),
|
||||
new BackupsAnonymousGrpcService(backupManager, backupMetrics, config.getAttachments().maxUploadSizeInBytes()),
|
||||
ExternalServiceCredentialsAnonymousGrpcService.create(accountsManager, config))
|
||||
.map(bindableService -> ServerInterceptors.intercept(bindableService,
|
||||
// Note: interceptors run in the reverse order they are added; the remote deprecation filter
|
||||
@@ -1091,8 +1096,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
new AccountControllerV2(accountsManager, changeNumberManager, phoneVerificationTokenManager,
|
||||
registrationLockVerificationManager, rateLimiters),
|
||||
new AttachmentControllerV4(rateLimiters, gcsAttachmentGenerator, tusAttachmentGenerator,
|
||||
experimentEnrollmentManager),
|
||||
new ArchiveController(accountsManager, backupAuthManager, backupManager, backupMetrics),
|
||||
experimentEnrollmentManager, config.getAttachments().maxUploadSizeInBytes()),
|
||||
new ArchiveController(accountsManager, backupAuthManager, backupManager, backupMetrics, config.getAttachments().maxUploadSizeInBytes()),
|
||||
new CallRoutingControllerV2(rateLimiters, cloudflareTurnCredentialsManager),
|
||||
new CallLinkController(rateLimiters, callingGenericZkSecretParams),
|
||||
new CallQualitySurveyController(callQualitySurveyManager),
|
||||
@@ -1120,7 +1125,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
zkSecretParams, zkProfileOperations, batchIdentityCheckExecutor),
|
||||
new ProvisioningController(rateLimiters, provisioningManager),
|
||||
new RegistrationController(accountsManager, phoneVerificationTokenManager, registrationLockVerificationManager,
|
||||
rateLimiters),
|
||||
rateLimiters, registrationFraudChecker),
|
||||
new RemoteConfigController(remoteConfigsManager, config.getRemoteConfigConfiguration().globalConfig(), clock),
|
||||
new SecureStorageController(storageCredentialsGenerator),
|
||||
new SecureValueRecovery2Controller(svr2CredentialsGenerator, accountsManager),
|
||||
|
||||
+1
-1
@@ -10,6 +10,6 @@ public interface AttachmentGenerator {
|
||||
|
||||
record Descriptor(Map<String, String> headers, String signedUploadLocation) {}
|
||||
|
||||
Descriptor generateAttachment(final String key);
|
||||
Descriptor generateAttachment(final String key, final long uploadLength);
|
||||
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.attachments;
|
||||
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Base64;
|
||||
|
||||
public class AttachmentUtil {
|
||||
public static final String CDN3_EXPERIMENT_NAME = "cdn3";
|
||||
|
||||
private AttachmentUtil() {}
|
||||
|
||||
public static String generateAttachmentKey(final SecureRandom secureRandom) {
|
||||
final byte[] bytes = new byte[15];
|
||||
secureRandom.nextBytes(bytes);
|
||||
return Base64.getUrlEncoder().encodeToString(bytes);
|
||||
}
|
||||
}
|
||||
+4
-5
@@ -24,16 +24,16 @@ public class GcsAttachmentGenerator implements AttachmentGenerator {
|
||||
private final CanonicalRequestSigner canonicalRequestSigner;
|
||||
|
||||
public GcsAttachmentGenerator(@Nonnull String domain, @Nonnull String email,
|
||||
int maxSizeInBytes, @Nonnull String pathPrefix, @Nonnull String rsaSigningKey)
|
||||
@Nonnull String pathPrefix, @Nonnull String rsaSigningKey)
|
||||
throws IOException, InvalidKeyException, InvalidKeySpecException {
|
||||
this.canonicalRequestGenerator = new CanonicalRequestGenerator(domain, email, maxSizeInBytes, pathPrefix);
|
||||
this.canonicalRequestGenerator = new CanonicalRequestGenerator(domain, email, pathPrefix);
|
||||
this.canonicalRequestSigner = new CanonicalRequestSigner(rsaSigningKey);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Descriptor generateAttachment(final String key) {
|
||||
public Descriptor generateAttachment(final String key, final long uploadLength) {
|
||||
final ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC);
|
||||
final CanonicalRequest canonicalRequest = canonicalRequestGenerator.createFor(key, now);
|
||||
final CanonicalRequest canonicalRequest = canonicalRequestGenerator.createFor(key, now, uploadLength);
|
||||
return new Descriptor(getHeaderMap(canonicalRequest), getSignedUploadLocation(canonicalRequest));
|
||||
}
|
||||
|
||||
@@ -50,5 +50,4 @@ public class GcsAttachmentGenerator implements AttachmentGenerator {
|
||||
"x-goog-resumable", "start");
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
+9
-16
@@ -6,8 +6,7 @@
|
||||
package org.whispersystems.textsecuregcm.attachments;
|
||||
|
||||
import org.apache.http.HttpHeaders;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
|
||||
import org.whispersystems.textsecuregcm.auth.JwtGenerator;
|
||||
import org.whispersystems.textsecuregcm.util.HeaderUtils;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Clock;
|
||||
@@ -18,28 +17,22 @@ public class TusAttachmentGenerator implements AttachmentGenerator {
|
||||
|
||||
private static final String ATTACHMENTS = "attachments";
|
||||
|
||||
final ExternalServiceCredentialsGenerator credentialsGenerator;
|
||||
final String tusUri;
|
||||
private final JwtGenerator jwtGenerator;
|
||||
private final String tusUri;
|
||||
|
||||
public TusAttachmentGenerator(final TusConfiguration cfg) {
|
||||
this.tusUri = cfg.uploadUri();
|
||||
this.credentialsGenerator = credentialsGenerator(Clock.systemUTC(), cfg);
|
||||
}
|
||||
|
||||
private static ExternalServiceCredentialsGenerator credentialsGenerator(final Clock clock, final TusConfiguration cfg) {
|
||||
return ExternalServiceCredentialsGenerator
|
||||
.builder(cfg.userAuthenticationTokenSharedSecret())
|
||||
.prependUsername(false)
|
||||
.withClock(clock)
|
||||
.build();
|
||||
this.jwtGenerator = new JwtGenerator(cfg.userAuthenticationTokenSharedSecret().value(), Clock.systemUTC());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Descriptor generateAttachment(final String key) {
|
||||
final ExternalServiceCredentials credentials = credentialsGenerator.generateFor(ATTACHMENTS + "/" + key);
|
||||
public Descriptor generateAttachment(final String key, final long uploadLength) {
|
||||
final String token = jwtGenerator.generateJwt(ATTACHMENTS, key,
|
||||
builder -> builder.withClaim(JwtGenerator.MAX_LENGTH_CLAIM_KEY, uploadLength));
|
||||
final String b64Key = Base64.getEncoder().encodeToString(key.getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
final Map<String, String> headers = Map.of(
|
||||
HttpHeaders.AUTHORIZATION, HeaderUtils.basicAuthHeader(credentials),
|
||||
HttpHeaders.AUTHORIZATION, HeaderUtils.bearerAuthHeader(token),
|
||||
"Upload-Metadata", String.format("filename %s", b64Key)
|
||||
);
|
||||
return new Descriptor(headers, tusUri + "/" + ATTACHMENTS);
|
||||
|
||||
+2
-2
@@ -6,10 +6,10 @@
|
||||
package org.whispersystems.textsecuregcm.attachments;
|
||||
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import jakarta.validation.constraints.Positive;
|
||||
import org.whispersystems.textsecuregcm.configuration.secrets.SecretBytes;
|
||||
import org.whispersystems.textsecuregcm.util.ExactlySize;
|
||||
|
||||
public record TusConfiguration(
|
||||
@ExactlySize(32) SecretBytes userAuthenticationTokenSharedSecret,
|
||||
@NotEmpty String uploadUri
|
||||
){}
|
||||
@NotEmpty String uploadUri){}
|
||||
+28
-6
@@ -16,13 +16,17 @@ import java.net.http.HttpResponse;
|
||||
import java.time.Duration;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import javax.annotation.Nullable;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.http.FaultTolerantHttpClient;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
|
||||
@@ -37,6 +41,8 @@ public class CloudflareTurnCredentialsManager {
|
||||
|
||||
private final FaultTolerantHttpClient cloudflareTurnClient;
|
||||
private final DnsNameResolver dnsNameResolver;
|
||||
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
|
||||
private final ExperimentEnrollmentManager experimentEnrollmentManager;
|
||||
|
||||
private final Duration clientCredentialTtl;
|
||||
|
||||
@@ -63,7 +69,9 @@ public class CloudflareTurnCredentialsManager {
|
||||
final ExecutorService executor,
|
||||
@Nullable final String retryConfigurationName,
|
||||
final ScheduledExecutorService retryExecutor,
|
||||
final DnsNameResolver dnsNameResolver) {
|
||||
final DnsNameResolver dnsNameResolver,
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
|
||||
final ExperimentEnrollmentManager experimentEnrollmentManager) {
|
||||
|
||||
this.cloudflareTurnClient = FaultTolerantHttpClient.newBuilder("cloudflare-turn", executor)
|
||||
.withCircuitBreaker(circuitBreakerConfigurationName)
|
||||
@@ -74,6 +82,8 @@ public class CloudflareTurnCredentialsManager {
|
||||
this.cloudflareTurnUrlsWithIps = cloudflareTurnUrlsWithIps;
|
||||
this.cloudflareTurnHostname = cloudflareTurnHostname;
|
||||
this.dnsNameResolver = dnsNameResolver;
|
||||
this.dynamicConfigurationManager = dynamicConfigurationManager;
|
||||
this.experimentEnrollmentManager = experimentEnrollmentManager;
|
||||
|
||||
final String credentialsRequestBody;
|
||||
|
||||
@@ -95,15 +105,27 @@ public class CloudflareTurnCredentialsManager {
|
||||
this.clientCredentialTtl = clientCredentialTtl;
|
||||
}
|
||||
|
||||
public TurnToken retrieveFromCloudflare() throws IOException {
|
||||
public TurnToken retrieveFromCloudflare(UUID accountUuid) throws IOException {
|
||||
final List<String> cloudflareTurnComposedUrls;
|
||||
final List<String> turnUrls;
|
||||
final List<String> turnUrlsWithIps;
|
||||
final String turnHostname;
|
||||
if (experimentEnrollmentManager.isEnrolled(accountUuid, "turnBeta")) {
|
||||
turnUrls = dynamicConfigurationManager.getConfiguration().getTurnConfiguration().getUrls();
|
||||
turnUrlsWithIps = dynamicConfigurationManager.getConfiguration().getTurnConfiguration().getUrlsWithIps();
|
||||
turnHostname = dynamicConfigurationManager.getConfiguration().getTurnConfiguration().getHostname();
|
||||
} else {
|
||||
turnUrls = this.cloudflareTurnUrls;
|
||||
turnUrlsWithIps = this.cloudflareTurnUrlsWithIps;
|
||||
turnHostname = this.cloudflareTurnHostname;
|
||||
}
|
||||
try {
|
||||
cloudflareTurnComposedUrls = dnsNameResolver.resolveAll(cloudflareTurnHostname).get().stream()
|
||||
cloudflareTurnComposedUrls = dnsNameResolver.resolveAll(turnHostname).get().stream()
|
||||
.map(i -> switch (i) {
|
||||
case Inet6Address i6 -> "[" + i6.getHostAddress() + "]";
|
||||
default -> i.getHostAddress();
|
||||
})
|
||||
.flatMap(i -> cloudflareTurnUrlsWithIps.stream().map(u -> u.formatted(i)))
|
||||
.flatMap(i -> turnUrlsWithIps.stream().map(u -> u.formatted(i)))
|
||||
.toList();
|
||||
} catch (Exception e) {
|
||||
throw new IOException(e);
|
||||
@@ -129,9 +151,9 @@ public class CloudflareTurnCredentialsManager {
|
||||
cloudflareTurnResponse.iceServers().username(),
|
||||
cloudflareTurnResponse.iceServers().credential(),
|
||||
clientCredentialTtl.toSeconds(),
|
||||
cloudflareTurnUrls == null ? Collections.emptyList() : cloudflareTurnUrls,
|
||||
turnUrls,
|
||||
cloudflareTurnComposedUrls,
|
||||
cloudflareTurnHostname
|
||||
turnHostname
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.auth;
|
||||
|
||||
import com.auth0.jwt.JWT;
|
||||
import com.auth0.jwt.JWTCreator;
|
||||
import com.auth0.jwt.algorithms.Algorithm;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/// Generates JWT tokens for external services to validate. This class always uses symmetric HMAC-SHA256 with a shared secret
|
||||
public class JwtGenerator {
|
||||
|
||||
public static final String MAX_LENGTH_CLAIM_KEY = "maxLen";
|
||||
public static final String SCOPE_CLAIM_KEY = "scope";
|
||||
|
||||
private final Algorithm algorithm;
|
||||
private final Clock clock;
|
||||
|
||||
public JwtGenerator(final byte[] sharedSecret, final Clock clock) {
|
||||
this.algorithm = Algorithm.HMAC256(sharedSecret);
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
public String generateJwt(final String audience, final String subject, Consumer<JWTCreator.Builder> claimCustomizer) {
|
||||
final Instant now = clock.instant();
|
||||
JWTCreator.Builder builder = JWT.create()
|
||||
.withAudience(audience)
|
||||
.withSubject(subject)
|
||||
.withIssuedAt(now);
|
||||
claimCustomizer.accept(builder);
|
||||
return builder.sign(algorithm);
|
||||
}
|
||||
}
|
||||
+1
-2
@@ -8,7 +8,6 @@ import io.grpc.Metadata;
|
||||
import io.grpc.ServerCall;
|
||||
import io.grpc.ServerCallHandler;
|
||||
import io.grpc.ServerInterceptor;
|
||||
import io.grpc.Status;
|
||||
import org.whispersystems.textsecuregcm.grpc.GrpcExceptions;
|
||||
import org.whispersystems.textsecuregcm.grpc.ServerInterceptorUtil;
|
||||
|
||||
@@ -22,7 +21,7 @@ public class ProhibitAuthenticationInterceptor implements ServerInterceptor {
|
||||
@Override
|
||||
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(final ServerCall<ReqT, RespT> call,
|
||||
final Metadata headers, final ServerCallHandler<ReqT, RespT> next) {
|
||||
final String authHeaderString = headers.get(Metadata.Key.of(RequireAuthenticationInterceptor.AUTHORIZATION_HEADER, Metadata.ASCII_STRING_MARSHALLER));
|
||||
final String authHeaderString = headers.get(RequireAuthenticationInterceptor.AUTHORIZATION_METADATA_KEY);
|
||||
if (authHeaderString != null) {
|
||||
return ServerInterceptorUtil.closeWithStatusException(call,
|
||||
GrpcExceptions.badAuthentication("The service forbids requests with an authentication header"));
|
||||
|
||||
+3
-4
@@ -11,7 +11,6 @@ import io.grpc.Metadata;
|
||||
import io.grpc.ServerCall;
|
||||
import io.grpc.ServerCallHandler;
|
||||
import io.grpc.ServerInterceptor;
|
||||
import io.grpc.Status;
|
||||
import java.util.Optional;
|
||||
import org.whispersystems.textsecuregcm.auth.AccountAuthenticator;
|
||||
import org.whispersystems.textsecuregcm.grpc.GrpcExceptions;
|
||||
@@ -26,7 +25,8 @@ import org.whispersystems.textsecuregcm.util.HeaderUtils;
|
||||
*/
|
||||
public class RequireAuthenticationInterceptor implements ServerInterceptor {
|
||||
|
||||
static final String AUTHORIZATION_HEADER = "authorization";
|
||||
public static final Metadata.Key<String> AUTHORIZATION_METADATA_KEY =
|
||||
Metadata.Key.of("authorization", Metadata.ASCII_STRING_MARSHALLER);
|
||||
|
||||
private final AccountAuthenticator authenticator;
|
||||
|
||||
@@ -37,8 +37,7 @@ public class RequireAuthenticationInterceptor implements ServerInterceptor {
|
||||
@Override
|
||||
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(final ServerCall<ReqT, RespT> call,
|
||||
final Metadata headers, final ServerCallHandler<ReqT, RespT> next) {
|
||||
final String authHeaderString = headers.get(
|
||||
Metadata.Key.of(AUTHORIZATION_HEADER, Metadata.ASCII_STRING_MARSHALLER));
|
||||
final String authHeaderString = headers.get(AUTHORIZATION_METADATA_KEY);
|
||||
|
||||
if (authHeaderString == null) {
|
||||
return ServerInterceptorUtil.closeWithStatusException(call,
|
||||
|
||||
@@ -6,7 +6,6 @@
|
||||
package org.whispersystems.textsecuregcm.backup;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.dropwizard.util.DataSize;
|
||||
import io.micrometer.core.instrument.DistributionSummary;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
@@ -46,6 +45,7 @@ import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecoveryClient;
|
||||
import org.whispersystems.textsecuregcm.attachments.AttachmentUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
@@ -60,8 +60,6 @@ import javax.annotation.Nullable;
|
||||
public class BackupManager {
|
||||
|
||||
static final String MESSAGE_BACKUP_NAME = "messageBackup";
|
||||
public static final long MAX_MESSAGE_BACKUP_OBJECT_SIZE = DataSize.mebibytes(101).toBytes();
|
||||
public static final long MAX_MEDIA_OBJECT_SIZE = DataSize.mebibytes(101).toBytes();
|
||||
|
||||
private static final String ZK_AUTHN_COUNTER_NAME = MetricsUtil.name(BackupManager.class, "authentication");
|
||||
private static final String ZK_AUTHZ_FAILURE_COUNTER_NAME = MetricsUtil.name(BackupManager.class,
|
||||
@@ -157,30 +155,33 @@ public class BackupManager {
|
||||
* If successful, this also updates the TTL of the backup.
|
||||
*
|
||||
* @param backupUser an already ZK authenticated backup user
|
||||
* @param uploadSize the maximum size of a message backup that can be uploaded with the returned form
|
||||
* @return the upload form
|
||||
* @throws BackupPermissionException if the credential does not have the correct level
|
||||
* @throws BackupWrongCredentialTypeException if the credential does not have the messages type
|
||||
*/
|
||||
public BackupUploadDescriptor createMessageBackupUploadDescriptor(
|
||||
final AuthenticatedBackupUser backupUser) throws BackupPermissionException, BackupWrongCredentialTypeException {
|
||||
final AuthenticatedBackupUser backupUser,
|
||||
final long uploadSize) throws BackupPermissionException, BackupWrongCredentialTypeException {
|
||||
checkBackupLevel(backupUser, BackupLevel.FREE);
|
||||
checkBackupCredentialType(backupUser, BackupCredentialType.MESSAGES);
|
||||
|
||||
// this could race with concurrent updates, but the only effect would be last-writer-wins on the timestamp
|
||||
backupsDb.addMessageBackup(backupUser).join();
|
||||
return cdn3BackupCredentialGenerator.generateUpload(cdnMessageBackupName(backupUser));
|
||||
return cdn3BackupCredentialGenerator.generateUpload(cdnMessageBackupName(backupUser), uploadSize);
|
||||
}
|
||||
|
||||
public BackupUploadDescriptor createTemporaryAttachmentUploadDescriptor(final AuthenticatedBackupUser backupUser)
|
||||
public BackupUploadDescriptor createTemporaryAttachmentUploadDescriptor(
|
||||
final AuthenticatedBackupUser backupUser,
|
||||
final long uploadSize)
|
||||
throws RateLimitExceededException, BackupPermissionException, BackupWrongCredentialTypeException {
|
||||
checkBackupLevel(backupUser, BackupLevel.PAID);
|
||||
checkBackupCredentialType(backupUser, BackupCredentialType.MEDIA);
|
||||
|
||||
rateLimiters.forDescriptor(RateLimiters.For.BACKUP_ATTACHMENT).validate(rateLimitKey(backupUser));
|
||||
final byte[] bytes = new byte[15];
|
||||
secureRandom.nextBytes(bytes);
|
||||
final String attachmentKey = Base64.getUrlEncoder().encodeToString(bytes);
|
||||
final AttachmentGenerator.Descriptor descriptor = tusAttachmentGenerator.generateAttachment(attachmentKey);
|
||||
final String attachmentKey = AttachmentUtil.generateAttachmentKey(secureRandom);
|
||||
final AttachmentGenerator.Descriptor descriptor =
|
||||
tusAttachmentGenerator.generateAttachment(attachmentKey, uploadSize);
|
||||
return new BackupUploadDescriptor(3, attachmentKey, descriptor.headers(), descriptor.signedUploadLocation());
|
||||
}
|
||||
|
||||
@@ -198,9 +199,9 @@ public class BackupManager {
|
||||
final long maxTotalMediaSize =
|
||||
dynamicConfigurationManager.getConfiguration().getBackupConfiguration().maxTotalMediaSize();
|
||||
|
||||
// Report that the backup is out of quota if it cannot store a max size media object
|
||||
// Report that the backup is out of quota if it is within 100MiB of the limit
|
||||
final boolean quotaExhausted = storedBackupAttributes.bytesUsed() >=
|
||||
(maxTotalMediaSize - BackupManager.MAX_MEDIA_OBJECT_SIZE);
|
||||
(maxTotalMediaSize - 1024 * 1024 * 100);
|
||||
|
||||
final Tags tags = Tags.of(
|
||||
UserAgentTagUtil.getPlatformTag(backupUser.userAgent()),
|
||||
@@ -333,13 +334,14 @@ public class BackupManager {
|
||||
*/
|
||||
public CopyQuota getCopyQuota(
|
||||
final AuthenticatedBackupUser backupUser,
|
||||
final List<CopyParameters> toCopy)
|
||||
final List<CopyParameters> toCopy,
|
||||
final long maximumSourceObjectSize)
|
||||
throws BackupWrongCredentialTypeException, BackupPermissionException, BackupInvalidArgumentException {
|
||||
checkBackupLevel(backupUser, BackupLevel.PAID);
|
||||
checkBackupCredentialType(backupUser, BackupCredentialType.MEDIA);
|
||||
|
||||
for (CopyParameters copyParameters : toCopy) {
|
||||
if (copyParameters.sourceLength() > MAX_MEDIA_OBJECT_SIZE || copyParameters.sourceLength() < 0) {
|
||||
if (copyParameters.sourceLength() > maximumSourceObjectSize || copyParameters.sourceLength() < 0) {
|
||||
throw new BackupInvalidArgumentException("Invalid sourceObject size");
|
||||
}
|
||||
}
|
||||
|
||||
+14
-32
@@ -7,8 +7,7 @@ package org.whispersystems.textsecuregcm.backup;
|
||||
|
||||
import org.apache.http.HttpHeaders;
|
||||
import org.whispersystems.textsecuregcm.attachments.TusConfiguration;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
|
||||
import org.whispersystems.textsecuregcm.auth.JwtGenerator;
|
||||
import org.whispersystems.textsecuregcm.util.HeaderUtils;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
@@ -17,47 +16,29 @@ import java.util.Base64;
|
||||
import java.util.Map;
|
||||
|
||||
public class Cdn3BackupCredentialGenerator {
|
||||
|
||||
public static final String CDN_PATH = "backups";
|
||||
public static final int BACKUP_CDN = 3;
|
||||
|
||||
private static String READ_PERMISSION = "read";
|
||||
private static String WRITE_PERMISSION = "write";
|
||||
private static String PERMISSION_SEPARATOR = "$";
|
||||
|
||||
// Write entities will be of the form 'write$backups/<string>
|
||||
private static final String WRITE_ENTITY_PREFIX = String.format("%s%s%s/", WRITE_PERMISSION, PERMISSION_SEPARATOR,
|
||||
CDN_PATH);
|
||||
// Read entities will be of the form 'read$backups/<string>
|
||||
private static final String READ_ENTITY_PREFIX = String.format("%s%s%s/", READ_PERMISSION, PERMISSION_SEPARATOR,
|
||||
CDN_PATH);
|
||||
|
||||
private final ExternalServiceCredentialsGenerator credentialsGenerator;
|
||||
private final String tusUri;
|
||||
private final JwtGenerator jwtGenerator;
|
||||
|
||||
public Cdn3BackupCredentialGenerator(final TusConfiguration cfg) {
|
||||
this.tusUri = cfg.uploadUri();
|
||||
this.credentialsGenerator = credentialsGenerator(Clock.systemUTC(), cfg);
|
||||
this.jwtGenerator = new JwtGenerator(cfg.userAuthenticationTokenSharedSecret().value(), Clock.systemUTC());
|
||||
}
|
||||
|
||||
private static ExternalServiceCredentialsGenerator credentialsGenerator(final Clock clock,
|
||||
final TusConfiguration cfg) {
|
||||
return ExternalServiceCredentialsGenerator
|
||||
.builder(cfg.userAuthenticationTokenSharedSecret())
|
||||
.prependUsername(false)
|
||||
.withClock(clock)
|
||||
.build();
|
||||
}
|
||||
|
||||
public BackupUploadDescriptor generateUpload(final String key) {
|
||||
public BackupUploadDescriptor generateUpload(final String key, final long uploadSize) {
|
||||
if (key.isBlank()) {
|
||||
throw new IllegalArgumentException("Upload descriptors must have non-empty keys");
|
||||
}
|
||||
final String entity = WRITE_ENTITY_PREFIX + key;
|
||||
final ExternalServiceCredentials credentials = credentialsGenerator.generateFor(entity);
|
||||
|
||||
final String token = jwtGenerator.generateJwt(CDN_PATH, key, builder -> builder
|
||||
.withClaim(JwtGenerator.MAX_LENGTH_CLAIM_KEY, uploadSize)
|
||||
.withClaim(JwtGenerator.SCOPE_CLAIM_KEY, "write"));
|
||||
|
||||
final String b64Key = Base64.getEncoder().encodeToString(key.getBytes(StandardCharsets.UTF_8));
|
||||
final Map<String, String> headers = Map.of(
|
||||
HttpHeaders.AUTHORIZATION, HeaderUtils.basicAuthHeader(credentials),
|
||||
HttpHeaders.AUTHORIZATION, HeaderUtils.bearerAuthHeader(token),
|
||||
"Upload-Metadata", String.format("filename %s", b64Key));
|
||||
|
||||
return new BackupUploadDescriptor(
|
||||
@@ -71,8 +52,9 @@ public class Cdn3BackupCredentialGenerator {
|
||||
if (hashedBackupId.isBlank()) {
|
||||
throw new IllegalArgumentException("Backup subdir name must be non-empty");
|
||||
}
|
||||
final ExternalServiceCredentials credentials = credentialsGenerator.generateFor(
|
||||
READ_ENTITY_PREFIX + hashedBackupId);
|
||||
return Map.of(HttpHeaders.AUTHORIZATION, HeaderUtils.basicAuthHeader(credentials));
|
||||
|
||||
final String token = jwtGenerator.generateJwt(CDN_PATH, hashedBackupId, builder -> builder
|
||||
.withClaim(JwtGenerator.SCOPE_CLAIM_KEY, "read"));
|
||||
return Map.of(HttpHeaders.AUTHORIZATION, HeaderUtils.bearerAuthHeader(token));
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,8 @@
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.backup;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
|
||||
/**
|
||||
* Descriptor for a single copy-and-encrypt operation
|
||||
*
|
||||
@@ -24,6 +26,25 @@ public record CopyParameters(
|
||||
* @return The size of the double-encrypted destination object after it is copied
|
||||
*/
|
||||
long destinationObjectSize() {
|
||||
return encryptionParameters().outputSize(sourceLength());
|
||||
return destinationObjectSize(sourceLength());
|
||||
}
|
||||
|
||||
/// Calculates the size of a ciphertext for a media object stored as part of a backup
|
||||
///
|
||||
/// @param inputSize the size, in bytes, of the plaintext media object
|
||||
///
|
||||
/// @return the size, in bytes, of the ciphertext of a media object with the given `inputSize`
|
||||
@VisibleForTesting
|
||||
static long destinationObjectSize(final int inputSize) {
|
||||
if (inputSize < 0) {
|
||||
throw new IllegalArgumentException("Size must be non-negative, but was " + inputSize);
|
||||
}
|
||||
|
||||
// AES-256 has 16-byte block size, and always adds a block if the plaintext is a multiple of the block size
|
||||
final long numBlocks = ((long) inputSize + 16) / 16;
|
||||
|
||||
// 16-byte IV will be generated and prepended to the ciphertext
|
||||
// IV + AES-256 encrypted data + HmacSHA256
|
||||
return 16 + (numBlocks * 16) + 32;
|
||||
}
|
||||
}
|
||||
-8
@@ -11,12 +11,4 @@ public record MediaEncryptionParameters(
|
||||
new SecretKeySpec(encryptionKey, "AES"),
|
||||
new SecretKeySpec(macKey, "HmacSHA256"));
|
||||
}
|
||||
|
||||
public int outputSize(final int inputSize) {
|
||||
// AES-256 has 16-byte block size, and always adds a block if the plaintext is a multiple of the block size
|
||||
final int numBlocks = (inputSize + 16) / 16;
|
||||
// 16-byte IV will be generated and prepended to the ciphertext
|
||||
// IV + AES-256 encrypted data + HmacSHA256
|
||||
return 16 + (numBlocks * 16) + 32;
|
||||
}
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import jakarta.validation.constraints.Positive;
|
||||
|
||||
public record AttachmentsConfiguration(@Positive long maxUploadSizeInBytes) {
|
||||
}
|
||||
-1
@@ -14,7 +14,6 @@ import org.whispersystems.textsecuregcm.configuration.secrets.SecretString;
|
||||
|
||||
public record GcpAttachmentsConfiguration(@NotBlank String domain,
|
||||
@NotBlank String email,
|
||||
@Min(1) int maxSizeInBytes,
|
||||
String pathPrefix,
|
||||
@NotNull SecretString rsaSigningKey) {
|
||||
@SuppressWarnings("unused")
|
||||
|
||||
+10
-1
@@ -12,6 +12,7 @@ import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import org.signal.chat.calling.GetTurnCredentialsResponseOrBuilder;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiterConfig;
|
||||
|
||||
public class DynamicConfiguration {
|
||||
@@ -30,7 +31,7 @@ public class DynamicConfiguration {
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
private DynamicRemoteDeprecationConfiguration remoteDeprecation = new DynamicRemoteDeprecationConfiguration();
|
||||
private DynamicRemoteDeprecationConfiguration remoteDeprecation = DynamicRemoteDeprecationConfiguration.DEFAULT;
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
@@ -76,6 +77,10 @@ public class DynamicConfiguration {
|
||||
@Valid
|
||||
private DynamicGrpcAllowListConfiguration grpcAllowList = new DynamicGrpcAllowListConfiguration();
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
private DynamicTurnConfiguration turn = new DynamicTurnConfiguration();
|
||||
|
||||
public Optional<DynamicExperimentEnrollmentConfiguration> getExperimentEnrollmentConfiguration(
|
||||
final String experimentName) {
|
||||
return Optional.ofNullable(experiments.get(experimentName));
|
||||
@@ -137,4 +142,8 @@ public class DynamicConfiguration {
|
||||
public DynamicGrpcAllowListConfiguration getGrpcAllowList() {
|
||||
return grpcAllowList;
|
||||
}
|
||||
|
||||
public DynamicTurnConfiguration getTurnConfiguration() {
|
||||
return turn;
|
||||
}
|
||||
}
|
||||
+21
-1
@@ -7,6 +7,7 @@ package org.whispersystems.textsecuregcm.configuration.dynamic;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import java.time.Duration;
|
||||
|
||||
public class DynamicMessagePersisterConfiguration {
|
||||
|
||||
@@ -19,12 +20,24 @@ public class DynamicMessagePersisterConfiguration {
|
||||
@JsonProperty
|
||||
private double trimOversizedQueueExtraRoomRatio = 1.5;
|
||||
|
||||
@JsonProperty
|
||||
private Duration nodeClaimTtl = Duration.ofMinutes(5);
|
||||
|
||||
@JsonProperty
|
||||
private Duration sleepBetweenNodes = Duration.ofSeconds(5);
|
||||
|
||||
public DynamicMessagePersisterConfiguration() {}
|
||||
|
||||
@VisibleForTesting
|
||||
public DynamicMessagePersisterConfiguration(final boolean persistenceEnabled, final double trimOversizedQueueExtraRoomRatio) {
|
||||
public DynamicMessagePersisterConfiguration(final boolean persistenceEnabled,
|
||||
final double trimOversizedQueueExtraRoomRatio,
|
||||
final Duration nodeClaimTtl,
|
||||
final Duration sleepBetweenNodes) {
|
||||
|
||||
this.persistenceEnabled = persistenceEnabled;
|
||||
this.trimOversizedQueueExtraRoomRatio = trimOversizedQueueExtraRoomRatio;
|
||||
this.nodeClaimTtl = nodeClaimTtl;
|
||||
this.sleepBetweenNodes = sleepBetweenNodes;
|
||||
}
|
||||
|
||||
public boolean isPersistenceEnabled() {
|
||||
@@ -35,4 +48,11 @@ public class DynamicMessagePersisterConfiguration {
|
||||
return trimOversizedQueueExtraRoomRatio;
|
||||
}
|
||||
|
||||
public Duration getNodeClaimTtl() {
|
||||
return nodeClaimTtl;
|
||||
}
|
||||
|
||||
public Duration getSleepBetweenNodes() {
|
||||
return sleepBetweenNodes;
|
||||
}
|
||||
}
|
||||
+30
-52
@@ -5,74 +5,52 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration.dynamic;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.vdurmont.semver4j.Semver;
|
||||
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
|
||||
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import java.util.Collections;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
|
||||
|
||||
public class DynamicRemoteDeprecationConfiguration {
|
||||
public record DynamicRemoteDeprecationConfiguration(
|
||||
@NotNull Map<ClientPlatform, Semver> minimumVersions,
|
||||
@NotNull Map<ClientPlatform, Semver> versionsPendingDeprecation,
|
||||
@NotNull Map<ClientPlatform, Set<Semver>> blockedVersions,
|
||||
@NotNull Map<ClientPlatform, Set<Semver>> versionsPendingBlock,
|
||||
@NotNull Boolean spqrEnforcementPending,
|
||||
@NotNull Boolean requireSpqr) {
|
||||
|
||||
@JsonProperty
|
||||
private Map<ClientPlatform, Semver> minimumVersions = Collections.emptyMap();
|
||||
public static DynamicRemoteDeprecationConfiguration DEFAULT = new DynamicRemoteDeprecationConfiguration(
|
||||
Collections.emptyMap(),
|
||||
Collections.emptyMap(),
|
||||
Collections.emptyMap(),
|
||||
Collections.emptyMap(),
|
||||
false,
|
||||
false);
|
||||
|
||||
@JsonProperty
|
||||
private Map<ClientPlatform, Semver> versionsPendingDeprecation = Collections.emptyMap();
|
||||
|
||||
@JsonProperty
|
||||
private Map<ClientPlatform, Set<Semver>> blockedVersions = Collections.emptyMap();
|
||||
|
||||
@JsonProperty
|
||||
private Map<ClientPlatform, Set<Semver>> versionsPendingBlock = Collections.emptyMap();
|
||||
|
||||
@JsonProperty
|
||||
private boolean unrecognizedUserAgentAllowed = true;
|
||||
|
||||
@VisibleForTesting
|
||||
public void setMinimumVersions(final Map<ClientPlatform, Semver> minimumVersions) {
|
||||
this.minimumVersions = minimumVersions;
|
||||
public DynamicRemoteDeprecationConfiguration {
|
||||
if (minimumVersions == null) {
|
||||
minimumVersions = DEFAULT.minimumVersions();
|
||||
}
|
||||
|
||||
public Map<ClientPlatform, Semver> getMinimumVersions() {
|
||||
return minimumVersions;
|
||||
if (versionsPendingDeprecation == null) {
|
||||
versionsPendingDeprecation = DEFAULT.versionsPendingDeprecation();
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
public void setVersionsPendingDeprecation(final Map<ClientPlatform, Semver> versionsPendingDeprecation) {
|
||||
this.versionsPendingDeprecation = versionsPendingDeprecation;
|
||||
if (blockedVersions == null) {
|
||||
blockedVersions = DEFAULT.blockedVersions();
|
||||
}
|
||||
|
||||
public Map<ClientPlatform, Semver> getVersionsPendingDeprecation() {
|
||||
return versionsPendingDeprecation;
|
||||
if (versionsPendingBlock == null) {
|
||||
versionsPendingBlock = DEFAULT.versionsPendingBlock();
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
public void setUnrecognizedUserAgentAllowed(final boolean allowUnrecognizedUserAgents) {
|
||||
this.unrecognizedUserAgentAllowed = allowUnrecognizedUserAgents;
|
||||
if (spqrEnforcementPending == null) {
|
||||
spqrEnforcementPending = DEFAULT.spqrEnforcementPending();
|
||||
}
|
||||
|
||||
public boolean isUnrecognizedUserAgentAllowed() {
|
||||
return unrecognizedUserAgentAllowed;
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
public void setBlockedVersions(final Map<ClientPlatform, Set<Semver>> blockedVersions) {
|
||||
this.blockedVersions = blockedVersions;
|
||||
}
|
||||
|
||||
public Map<ClientPlatform, Set<Semver>> getBlockedVersions() {
|
||||
return blockedVersions;
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
public void setVersionsPendingBlock(final Map<ClientPlatform, Set<Semver>> versionsPendingBlock) {
|
||||
this.versionsPendingBlock = versionsPendingBlock;
|
||||
}
|
||||
|
||||
public Map<ClientPlatform, Set<Semver>> getVersionsPendingBlock() {
|
||||
return versionsPendingBlock;
|
||||
if (requireSpqr == null) {
|
||||
requireSpqr = DEFAULT.requireSpqr();
|
||||
}
|
||||
}
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration.dynamic;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import javax.annotation.Nullable;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
public class DynamicTurnConfiguration {
|
||||
|
||||
@JsonProperty
|
||||
@NotNull
|
||||
@Valid
|
||||
private List<@NotBlank String> urls = Collections.emptyList();
|
||||
|
||||
@JsonProperty
|
||||
@NotNull
|
||||
@Valid
|
||||
private List<@NotBlank String> urlsWithIps = Collections.emptyList();
|
||||
|
||||
@JsonProperty
|
||||
@Nullable
|
||||
private String hostname = null;
|
||||
|
||||
public DynamicTurnConfiguration() {}
|
||||
|
||||
public List<String> getUrls() {
|
||||
return urls;
|
||||
}
|
||||
|
||||
public List<String> getUrlsWithIps() {
|
||||
return urlsWithIps;
|
||||
}
|
||||
|
||||
public @Nullable String getHostname() {
|
||||
return hostname;
|
||||
}
|
||||
}
|
||||
+27
-11
@@ -102,17 +102,20 @@ public class ArchiveController {
|
||||
private final BackupAuthManager backupAuthManager;
|
||||
private final BackupManager backupManager;
|
||||
private final BackupMetrics backupMetrics;
|
||||
private final long maxAttachmentSize;
|
||||
|
||||
public ArchiveController(
|
||||
final AccountsManager accountsManager,
|
||||
final BackupAuthManager backupAuthManager,
|
||||
final BackupManager backupManager,
|
||||
final BackupMetrics backupMetrics) {
|
||||
final BackupMetrics backupMetrics,
|
||||
final long maxAttachmentSize) {
|
||||
|
||||
this.accountsManager = accountsManager;
|
||||
this.backupAuthManager = backupAuthManager;
|
||||
this.backupManager = backupManager;
|
||||
this.backupMetrics = backupMetrics;
|
||||
this.maxAttachmentSize = maxAttachmentSize;
|
||||
}
|
||||
|
||||
public record SetBackupIdRequest(
|
||||
@@ -566,8 +569,11 @@ public class ArchiveController {
|
||||
@Path("/upload/form")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Operation(
|
||||
summary = "Fetch message backup upload form",
|
||||
description = "Retrieve an upload form that can be used to perform a resumable upload of a message backup.")
|
||||
summary = "Fetch message backup upload form", description = """
|
||||
Retrieve an upload form that can be used to perform a resumable upload of a message backup.
|
||||
|
||||
Uploads with the returned form will be limited to a maximum size of the provided uploadLength.
|
||||
""")
|
||||
@ApiResponse(responseCode = "200", content = @Content(schema = @Schema(implementation = UploadDescriptorResponse.class)))
|
||||
@ApiResponse(responseCode = "429", description = "Rate limited.")
|
||||
@ApiResponse(responseCode = "413", description = "The provided uploadLength is larger than the maximum supported upload size. The maximum upload size is subject to change.")
|
||||
@@ -596,7 +602,7 @@ public class ArchiveController {
|
||||
backupManager.authenticateBackupUser(presentation.presentation, signature.signature, userAgent);
|
||||
|
||||
final boolean oversize = uploadLength
|
||||
.map(length -> length > BackupManager.MAX_MESSAGE_BACKUP_OBJECT_SIZE)
|
||||
.map(length -> length > maxAttachmentSize)
|
||||
.orElse(false);
|
||||
|
||||
backupMetrics.updateMessageBackupSizeDistribution(backupUser, oversize, uploadLength);
|
||||
@@ -604,7 +610,7 @@ public class ArchiveController {
|
||||
throw new ClientErrorException("exceeded maximum uploadLength", Response.Status.REQUEST_ENTITY_TOO_LARGE);
|
||||
}
|
||||
final BackupUploadDescriptor uploadDescriptor =
|
||||
backupManager.createMessageBackupUploadDescriptor(backupUser);
|
||||
backupManager.createMessageBackupUploadDescriptor(backupUser, uploadLength.orElse(maxAttachmentSize));
|
||||
return new UploadDescriptorResponse(
|
||||
uploadDescriptor.cdn(),
|
||||
uploadDescriptor.key(),
|
||||
@@ -621,32 +627,42 @@ public class ArchiveController {
|
||||
Retrieve an upload form that can be used to perform a resumable upload of an attachment. After uploading, the
|
||||
attachment can be copied into the backup at PUT /archives/media/.
|
||||
|
||||
Like the account authenticated version at /attachments, the uploaded object is only temporary.
|
||||
Like the account authenticated version at /attachments, the uploaded object is only temporary. Uploads with
|
||||
the returned form will be limited to a maximum size of the provided uploadLength.
|
||||
""")
|
||||
@ApiResponse(responseCode = "200", content = @Content(schema = @Schema(implementation = UploadDescriptorResponse.class)))
|
||||
@ApiResponse(responseCode = "429", description = "Rate limited.")
|
||||
@ApiResponse(responseCode = "413", description = "The provided uploadLength is larger than the maximum supported upload size. The maximum upload size is subject to change and is governed by `global.attachments.maxBytes`.")
|
||||
@ApiResponseZkAuth
|
||||
@ManagedAsync
|
||||
public UploadDescriptorResponse uploadTemporaryAttachment(
|
||||
@Auth final Optional<AuthenticatedDevice> account,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
|
||||
|
||||
|
||||
@Parameter(description = BackupAuthCredentialPresentationHeader.DESCRIPTION, schema = @Schema(implementation = String.class))
|
||||
@NotNull
|
||||
@HeaderParam(X_SIGNAL_ZK_AUTH) final ArchiveController.BackupAuthCredentialPresentationHeader presentation,
|
||||
|
||||
@Parameter(description = BackupAuthCredentialPresentationSignature.DESCRIPTION, schema = @Schema(implementation = String.class))
|
||||
@NotNull
|
||||
@HeaderParam(X_SIGNAL_ZK_AUTH_SIGNATURE) final BackupAuthCredentialPresentationSignature signature)
|
||||
@HeaderParam(X_SIGNAL_ZK_AUTH_SIGNATURE) final BackupAuthCredentialPresentationSignature signature,
|
||||
|
||||
@Parameter(description = "The size of the temporary attachment to upload in bytes")
|
||||
@QueryParam("uploadLength") final Optional<Long> uploadLength)
|
||||
throws RateLimitExceededException, BackupFailedZkAuthenticationException, BackupWrongCredentialTypeException, BackupPermissionException {
|
||||
if (account.isPresent()) {
|
||||
throw new BadRequestException("must not use authenticated connection for anonymous operations");
|
||||
}
|
||||
final AuthenticatedBackupUser backupUser =
|
||||
backupManager.authenticateBackupUser(presentation.presentation, signature.signature, userAgent);
|
||||
|
||||
final boolean oversize = uploadLength.map(length -> length > maxAttachmentSize).orElse(false);
|
||||
if (oversize) {
|
||||
throw new ClientErrorException("exceeded maximum uploadLength", Response.Status.REQUEST_ENTITY_TOO_LARGE);
|
||||
}
|
||||
|
||||
final BackupUploadDescriptor uploadDescriptor =
|
||||
backupManager.createTemporaryAttachmentUploadDescriptor(backupUser);
|
||||
backupManager.createTemporaryAttachmentUploadDescriptor(backupUser, uploadLength.orElse(maxAttachmentSize));
|
||||
return new UploadDescriptorResponse(
|
||||
uploadDescriptor.cdn(),
|
||||
uploadDescriptor.key(),
|
||||
@@ -741,7 +757,7 @@ public class ArchiveController {
|
||||
final AuthenticatedBackupUser backupUser =
|
||||
backupManager.authenticateBackupUser(presentation.presentation, signature.signature, userAgent);
|
||||
final BackupManager.CopyQuota copyQuota =
|
||||
backupManager.getCopyQuota(backupUser, List.of(copyMediaRequest.toCopyParameters()));
|
||||
backupManager.getCopyQuota(backupUser, List.of(copyMediaRequest.toCopyParameters()), maxAttachmentSize);
|
||||
final CopyResult copyResult = backupManager.copyToBackup(copyQuota).next()
|
||||
.blockOptional()
|
||||
.orElseThrow(() -> new IllegalStateException("Non empty copy request must return result"));
|
||||
@@ -844,7 +860,7 @@ public class ArchiveController {
|
||||
final Stream<CopyParameters> copyParams = copyMediaRequest.items().stream().map(CopyMediaRequest::toCopyParameters);
|
||||
final AuthenticatedBackupUser backupUser =
|
||||
backupManager.authenticateBackupUser(presentation.presentation, signature.signature, userAgent);
|
||||
final BackupManager.CopyQuota copyQuota = backupManager.getCopyQuota(backupUser, copyParams.toList());
|
||||
final BackupManager.CopyQuota copyQuota = backupManager.getCopyQuota(backupUser, copyParams.toList(), maxAttachmentSize);
|
||||
final List<CopyMediaBatchResponse.Entry> copyResults = backupManager.copyToBackup(copyQuota)
|
||||
.doOnNext(result -> backupMetrics.updateCopyCounter(result, UserAgentTagUtil.getPlatformTag(userAgent)))
|
||||
.map(CopyMediaBatchResponse.Entry::fromCopyResult)
|
||||
|
||||
+45
-19
@@ -7,18 +7,25 @@ package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
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 jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.Positive;
|
||||
import jakarta.ws.rs.ClientErrorException;
|
||||
import jakarta.ws.rs.GET;
|
||||
import jakarta.ws.rs.Path;
|
||||
import jakarta.ws.rs.Produces;
|
||||
import jakarta.ws.rs.QueryParam;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Base64;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import javax.annotation.Nonnull;
|
||||
import org.whispersystems.textsecuregcm.attachments.AttachmentGenerator;
|
||||
import org.whispersystems.textsecuregcm.attachments.AttachmentUtil;
|
||||
import org.whispersystems.textsecuregcm.attachments.GcsAttachmentGenerator;
|
||||
import org.whispersystems.textsecuregcm.attachments.TusAttachmentGenerator;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
@@ -36,10 +43,10 @@ import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
@Tag(name = "Attachments")
|
||||
public class AttachmentControllerV4 {
|
||||
|
||||
public static final String CDN3_EXPERIMENT_NAME = "cdn3";
|
||||
|
||||
private final ExperimentEnrollmentManager experimentEnrollmentManager;
|
||||
private final RateLimiter rateLimiter;
|
||||
private final RateLimiter countRateLimiter;
|
||||
private final RateLimiter bytesRateLimiter;
|
||||
private final long maxUploadLength;
|
||||
|
||||
private final Map<Integer, AttachmentGenerator> attachmentGenerators;
|
||||
|
||||
@@ -50,9 +57,12 @@ public class AttachmentControllerV4 {
|
||||
final RateLimiters rateLimiters,
|
||||
final GcsAttachmentGenerator gcsAttachmentGenerator,
|
||||
final TusAttachmentGenerator tusAttachmentGenerator,
|
||||
final ExperimentEnrollmentManager experimentEnrollmentManager) {
|
||||
this.rateLimiter = rateLimiters.getAttachmentLimiter();
|
||||
final ExperimentEnrollmentManager experimentEnrollmentManager,
|
||||
final long maxUploadLength) {
|
||||
this.countRateLimiter = rateLimiters.getAttachmentLimiter();
|
||||
this.bytesRateLimiter = rateLimiters.getAttachmentBytesLimiter();
|
||||
this.experimentEnrollmentManager = experimentEnrollmentManager;
|
||||
this.maxUploadLength = maxUploadLength;
|
||||
this.secureRandom = new SecureRandom();
|
||||
this.attachmentGenerators = Map.of(
|
||||
2, gcsAttachmentGenerator,
|
||||
@@ -68,28 +78,44 @@ public class AttachmentControllerV4 {
|
||||
description = """
|
||||
Retrieve an upload form that can be used to perform a resumable upload. The response will include a cdn number
|
||||
indicating what protocol should be used to perform the upload.
|
||||
|
||||
Uploads with the returned form will be limited to a maximum size of the provided uploadLength.
|
||||
"""
|
||||
)
|
||||
@ApiResponse(responseCode = "200", description = "Success, response body includes upload form", useReturnTypeSchema = true)
|
||||
@ApiResponse(responseCode = "413", description = "Too many attempts", headers = @Header(
|
||||
name = "Retry-After",
|
||||
description = "If present, an positive integer indicating the number of seconds before a subsequent attempt could succeed"))
|
||||
@ApiResponse(responseCode = "400", description = "The provided uploadLength was not valid")
|
||||
@ApiResponse(responseCode = "413", description = "The provided uploadLength is larger than the maximum supported upload size. The maximum upload size is subject to change and is governed by `global.attachments.maxBytes`.")
|
||||
@ApiResponse(responseCode = "429", description = "Too many attempts", headers = @Header(
|
||||
name = "Retry-After",
|
||||
description = "If present, an positive integer indicating the number of seconds before a subsequent attempt could succeed"))
|
||||
public AttachmentDescriptorV3 getAttachmentUploadForm(@Auth AuthenticatedDevice auth)
|
||||
public AttachmentDescriptorV3 getAttachmentUploadForm(
|
||||
@Auth AuthenticatedDevice auth,
|
||||
@Parameter(description = "The size of the attachment to upload in bytes")
|
||||
@QueryParam("uploadLength") final @Valid Optional<@Positive Long> maybeUploadLength)
|
||||
throws RateLimitExceededException {
|
||||
rateLimiter.validate(auth.accountIdentifier());
|
||||
final String key = generateAttachmentKey();
|
||||
final boolean useCdn3 = this.experimentEnrollmentManager.isEnrolled(auth.accountIdentifier(), CDN3_EXPERIMENT_NAME);
|
||||
|
||||
final long uploadLength = maybeUploadLength.orElse(maxUploadLength);
|
||||
if (uploadLength > maxUploadLength) {
|
||||
throw new ClientErrorException("exceeded maximum uploadLength", Response.Status.REQUEST_ENTITY_TOO_LARGE);
|
||||
}
|
||||
|
||||
countRateLimiter.validate(auth.accountIdentifier());
|
||||
if (maybeUploadLength.isPresent()) {
|
||||
// Ideally we'd check these two rate limits transactionally and only update them if both permits were acquired.
|
||||
// However, just undoing the first modification if the second one fails is close enough for our purposes
|
||||
try {
|
||||
bytesRateLimiter.validate(auth.accountIdentifier(), maybeUploadLength.get());
|
||||
} catch (RateLimitExceededException e) {
|
||||
countRateLimiter.restorePermits(auth.accountIdentifier(), 1);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
final String key = AttachmentUtil.generateAttachmentKey(secureRandom);
|
||||
final boolean useCdn3 = this.experimentEnrollmentManager.isEnrolled(auth.accountIdentifier(), AttachmentUtil.CDN3_EXPERIMENT_NAME);
|
||||
int cdn = useCdn3 ? 3 : 2;
|
||||
final AttachmentGenerator.Descriptor descriptor = this.attachmentGenerators.get(cdn).generateAttachment(key);
|
||||
final AttachmentGenerator.Descriptor descriptor = this.attachmentGenerators.get(cdn).generateAttachment(key, uploadLength);
|
||||
return new AttachmentDescriptorV3(cdn, key, descriptor.headers(), descriptor.signedUploadLocation());
|
||||
}
|
||||
|
||||
private String generateAttachmentKey() {
|
||||
final byte[] bytes = new byte[15];
|
||||
secureRandom.nextBytes(bytes);
|
||||
return Base64.getUrlEncoder().encodeToString(bytes);
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -60,7 +60,7 @@ public class CallRoutingControllerV2 {
|
||||
rateLimiters.getCallEndpointLimiter().validate(auth.accountIdentifier());
|
||||
|
||||
try {
|
||||
return new GetCallingRelaysResponse(List.of(cloudflareTurnCredentialsManager.retrieveFromCloudflare()));
|
||||
return new GetCallingRelaysResponse(List.of(cloudflareTurnCredentialsManager.retrieveFromCloudflare(auth.accountIdentifier())));
|
||||
} catch (final Exception e) {
|
||||
CLOUDFLARE_TURN_ERROR_COUNTER.increment();
|
||||
throw e;
|
||||
|
||||
+4
@@ -408,6 +408,10 @@ public class DeviceController {
|
||||
}
|
||||
|
||||
private static boolean isCapabilityDowngrade(final Account account, final Set<DeviceCapability> capabilities) {
|
||||
if (!capabilities.containsAll(DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
final Set<DeviceCapability> requiredCapabilities = Arrays.stream(DeviceCapability.values())
|
||||
// `ALWAYS_CAPABLE` capabilities are always assumed to be present, so we don't require callers to specify them
|
||||
.filter(capability -> capability.getAccountCapabilityMode() != DeviceCapability.AccountCapabilityMode.ALWAYS_CAPABLE)
|
||||
|
||||
+17
-13
@@ -398,34 +398,38 @@ public class KeysController {
|
||||
}
|
||||
|
||||
private List<Device> parseDeviceId(String deviceId, Account account) {
|
||||
return parseDeviceId(deviceId)
|
||||
.map(id -> account.getDevice(id).map(List::of).orElse(List.of()))
|
||||
.orElseGet(account::getDevices);
|
||||
}
|
||||
|
||||
private Optional<Byte> parseDeviceId(final String deviceId) {
|
||||
if (deviceId.equals("*")) {
|
||||
return account.getDevices();
|
||||
return Optional.empty();
|
||||
}
|
||||
try {
|
||||
byte id = Byte.parseByte(deviceId);
|
||||
return account.getDevice(id).map(List::of).orElse(List.of());
|
||||
return Optional.of(Byte.parseByte(deviceId));
|
||||
} catch (NumberFormatException e) {
|
||||
throw new WebApplicationException(Response.status(422).build());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private String getPreKeysLimiterKey(
|
||||
final Account account,
|
||||
final AuthenticatedDevice authenticatedDevice,
|
||||
final ServiceIdentifier targetIdentifier,
|
||||
final Account targetAccount,
|
||||
final String targetDeviceId) {
|
||||
final String targetRegistrationId = targetDeviceId.equals("*")
|
||||
? "*"
|
||||
: String.valueOf(
|
||||
parseDeviceId(targetDeviceId, targetAccount).getFirst().getRegistrationId(targetIdentifier.identityType()));
|
||||
|
||||
return String.format("%s.%s__%s.%s.%s",
|
||||
final Optional<Byte> parsedTargetDeviceId = parseDeviceId(targetDeviceId);
|
||||
final Optional<Integer> targetRegistrationId = parsedTargetDeviceId
|
||||
.flatMap(targetAccount::getDevice)
|
||||
.map(device -> device.getRegistrationId(targetIdentifier.identityType()));
|
||||
return RateLimitKeys.preKeyLimiterKey(
|
||||
account.getUuid(),
|
||||
authenticatedDevice.deviceId(),
|
||||
targetIdentifier.uuid(),
|
||||
targetDeviceId,
|
||||
targetRegistrationId
|
||||
);
|
||||
targetIdentifier,
|
||||
parsedTargetDeviceId, targetRegistrationId);
|
||||
}
|
||||
|
||||
}
|
||||
+33
-51
@@ -58,8 +58,8 @@ import org.whispersystems.textsecuregcm.storage.IssuedReceiptsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.OneTimeDonationsManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.BraintreeManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.ChargeFailure;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PayPalDonationsTranslator;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.CustomerAwareSubscriptionPaymentProcessor;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PayPalDonationsTranslator;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentDetails;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentMethod;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
|
||||
@@ -118,17 +118,18 @@ public class OneTimeDonationController {
|
||||
|
||||
public static class CreateBoostRequest {
|
||||
|
||||
@Schema(required = true, maxLength = 3, minLength = 3)
|
||||
@Schema(maxLength = 3, minLength = 3)
|
||||
@NotEmpty
|
||||
@ExactlySize(3)
|
||||
public String currency;
|
||||
|
||||
@Schema(required = true, minimum = "1", description = "The amount to pay in the [currency's minor unit](https://docs.stripe.com/currencies#minor-units)")
|
||||
@Schema(minimum = "1", description = "The amount to pay in the [currency's minor unit](https://docs.stripe.com/currencies#minor-units)", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
@Min(1)
|
||||
public long amount;
|
||||
|
||||
@Schema(description = "The level for the boost payment. Assumed to be the boost level if missing")
|
||||
public Long level;
|
||||
@Schema(description = "The level for the boost payment", defaultValue = "1", minimum = "1", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
@Min(1)
|
||||
public long level = 1;
|
||||
|
||||
@Schema(description = "The payment method", defaultValue = "CARD")
|
||||
public PaymentMethod paymentMethod = PaymentMethod.CARD;
|
||||
@@ -160,12 +161,6 @@ public class OneTimeDonationController {
|
||||
properties = {
|
||||
@StringToClassMapItem(key = "error", value = String.class)
|
||||
})))
|
||||
@ApiResponse(responseCode = "409", description = "Provided level does not match the currency/amount combination",
|
||||
content = @Content(schema = @Schema(
|
||||
type = "object",
|
||||
properties = {
|
||||
@StringToClassMapItem(key = "error", value = String.class)
|
||||
})))
|
||||
public CompletableFuture<Response> createBoostPaymentIntent(
|
||||
@Auth Optional<AuthenticatedDevice> authenticatedAccount,
|
||||
@NotNull @Valid CreateBoostRequest request,
|
||||
@@ -175,45 +170,37 @@ public class OneTimeDonationController {
|
||||
throw new ForbiddenException("must not use authenticated connection for one-time donation operations");
|
||||
}
|
||||
|
||||
return CompletableFuture.runAsync(() -> {
|
||||
if (request.level == null) {
|
||||
request.level = oneTimeDonationConfiguration.boost().level();
|
||||
}
|
||||
BigDecimal amount = BigDecimal.valueOf(request.amount);
|
||||
if (request.level == oneTimeDonationConfiguration.gift().level()) {
|
||||
BigDecimal amountConfigured = oneTimeDonationConfiguration.currencies()
|
||||
.get(request.currency.toLowerCase(Locale.ROOT)).gift();
|
||||
if (amountConfigured == null ||
|
||||
SubscriptionCurrencyUtil.convertConfiguredAmountToStripeAmount(request.currency, amountConfigured)
|
||||
.compareTo(amount) != 0) {
|
||||
throw new WebApplicationException(
|
||||
Response.status(Response.Status.CONFLICT).entity(Map.of("error", "level_amount_mismatch")).build());
|
||||
}
|
||||
}
|
||||
validateRequestCurrencyAmount(request, amount, stripeManager);
|
||||
})
|
||||
.thenCompose(unused -> stripeManager.createPaymentIntent(request.currency, request.amount, request.level,
|
||||
return CompletableFuture.runAsync(() ->
|
||||
validateRequestCurrencyAmount(request, BigDecimal.valueOf(request.amount), stripeManager))
|
||||
.thenCompose(_ -> stripeManager.createPaymentIntent(request.currency, request.amount, request.level,
|
||||
getClientPlatform(userAgent)))
|
||||
.thenApply(paymentIntent -> Response.ok(new CreateBoostResponse(paymentIntent.getClientSecret())).build());
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates that the currency is supported by the {@code manager} and {@code request.paymentMethod} and that the
|
||||
* amount meets minimum and maximum constraints.
|
||||
* Validates that the request level is valid, the currency is supported by the {@code manager} and {@code request.paymentMethod},
|
||||
* and that the amount meets minimum and maximum constraints.
|
||||
*
|
||||
* @throws BadRequestException indicates validation failed. Inspect {@code response.error} for details
|
||||
*/
|
||||
private void validateRequestCurrencyAmount(CreateBoostRequest request, BigDecimal amount,
|
||||
CustomerAwareSubscriptionPaymentProcessor manager) {
|
||||
private void validateRequestCurrencyAmount(final CreateBoostRequest request, final BigDecimal amount,
|
||||
final CustomerAwareSubscriptionPaymentProcessor manager) {
|
||||
|
||||
if (!(request.level == oneTimeDonationConfiguration.gift().level()
|
||||
|| request.level == oneTimeDonationConfiguration.boost().level())) {
|
||||
throw new BadRequestException(
|
||||
Response.status(Response.Status.BAD_REQUEST).entity(Map.of("error", "invalid_level")).build());
|
||||
}
|
||||
|
||||
if (!manager.getSupportedCurrenciesForPaymentMethod(request.paymentMethod)
|
||||
.contains(request.currency.toLowerCase(Locale.ROOT))) {
|
||||
throw new BadRequestException(Response.status(Response.Status.BAD_REQUEST)
|
||||
.entity(Map.of("error", "unsupported_currency")).build());
|
||||
}
|
||||
|
||||
BigDecimal minCurrencyAmountMajorUnits = oneTimeDonationConfiguration.currencies()
|
||||
final BigDecimal minCurrencyAmountMajorUnits = oneTimeDonationConfiguration.currencies()
|
||||
.get(request.currency.toLowerCase(Locale.ROOT)).minimum();
|
||||
BigDecimal minCurrencyAmountMinorUnits = SubscriptionCurrencyUtil.convertConfiguredAmountToApiAmount(
|
||||
final BigDecimal minCurrencyAmountMinorUnits = SubscriptionCurrencyUtil.convertConfiguredAmountToApiAmount(
|
||||
request.currency,
|
||||
minCurrencyAmountMajorUnits);
|
||||
if (minCurrencyAmountMinorUnits.compareTo(amount) > 0) {
|
||||
@@ -255,21 +242,15 @@ public class OneTimeDonationController {
|
||||
public CompletableFuture<Response> createPayPalBoost(
|
||||
@Auth Optional<AuthenticatedDevice> authenticatedAccount,
|
||||
@NotNull @Valid CreatePayPalBoostRequest request,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
|
||||
@Context ContainerRequestContext containerRequestContext) {
|
||||
|
||||
if (authenticatedAccount.isPresent()) {
|
||||
throw new ForbiddenException("must not use authenticated connection for one-time donation operations");
|
||||
}
|
||||
|
||||
return CompletableFuture.runAsync(() -> {
|
||||
if (request.level == null) {
|
||||
request.level = oneTimeDonationConfiguration.boost().level();
|
||||
}
|
||||
|
||||
validateRequestCurrencyAmount(request, BigDecimal.valueOf(request.amount), braintreeManager);
|
||||
})
|
||||
.thenCompose(unused -> {
|
||||
return CompletableFuture.runAsync(() ->
|
||||
validateRequestCurrencyAmount(request, BigDecimal.valueOf(request.amount), braintreeManager))
|
||||
.thenCompose(_ -> {
|
||||
final List<Locale> acceptableLanguages =
|
||||
HeaderUtils.getAcceptableLanguagesForRequest(containerRequestContext);
|
||||
|
||||
@@ -300,6 +281,10 @@ public class OneTimeDonationController {
|
||||
public String paymentId; // PAYID-…
|
||||
@NotEmpty
|
||||
public String paymentToken; // EC-…
|
||||
|
||||
public ConfirmPayPalBoostRequest() {
|
||||
super.paymentMethod = PaymentMethod.PAYPAL;
|
||||
}
|
||||
}
|
||||
|
||||
record ConfirmPayPalBoostResponse(String paymentId) {}
|
||||
@@ -317,12 +302,9 @@ public class OneTimeDonationController {
|
||||
throw new ForbiddenException("must not use authenticated connection for one-time donation operations");
|
||||
}
|
||||
|
||||
return CompletableFuture.runAsync(() -> {
|
||||
if (request.level == null) {
|
||||
request.level = oneTimeDonationConfiguration.boost().level();
|
||||
}
|
||||
})
|
||||
.thenCompose(unused -> braintreeManager.captureOneTimePayment(request.payerId, request.paymentId,
|
||||
return CompletableFuture.runAsync(() ->
|
||||
validateRequestCurrencyAmount(request, BigDecimal.valueOf(request.amount), braintreeManager))
|
||||
.thenCompose(_ -> braintreeManager.captureOneTimePayment(request.payerId, request.paymentId,
|
||||
request.paymentToken, request.currency, request.amount, request.level, getClientPlatform(userAgent)))
|
||||
.thenCompose(
|
||||
chargeSuccessDetails -> oneTimeDonationsManager.putPaidAt(chargeSuccessDetails.paymentId(), Instant.now()))
|
||||
@@ -412,7 +394,7 @@ public class OneTimeDonationController {
|
||||
final long finalLevel = level;
|
||||
return issuedReceiptsManager.recordIssuance(paymentDetails.id(), request.processor,
|
||||
receiptCredentialRequest, clock.instant())
|
||||
.thenCompose(unused -> oneTimeDonationsManager.getPaidAt(paymentDetails.id(), paymentDetails.created()))
|
||||
.thenCompose(_ -> oneTimeDonationsManager.getPaidAt(paymentDetails.id(), paymentDetails.created()))
|
||||
.thenApply(paidAt -> {
|
||||
Instant expiration = paidAt
|
||||
.plus(levelExpiration)
|
||||
|
||||
+77
-19
@@ -11,6 +11,10 @@ import com.google.common.base.Preconditions;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.media.Content;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
@@ -72,7 +76,6 @@ import org.whispersystems.textsecuregcm.entities.BaseProfileResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.BatchIdentityCheckRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.BatchIdentityCheckResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.CreateProfileRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.CredentialProfileResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.ExpiringProfileKeyCredentialProfileResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.ProfileAvatarUploadAttributes;
|
||||
import org.whispersystems.textsecuregcm.entities.VersionedProfileResponse;
|
||||
@@ -151,6 +154,18 @@ public class ProfileController {
|
||||
@PUT
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Operation(
|
||||
summary = "Update profile",
|
||||
description = "Updates an account’s profile. Must be authenticated.")
|
||||
@ApiResponse(responseCode = "200", description = "The profile was updated successfully.",
|
||||
content = @Content(schema = @Schema(
|
||||
implementation = ProfileAvatarUploadAttributes.class,
|
||||
description = "If the request changed the avatar, the response body contains an upload form.")))
|
||||
@ApiResponse(responseCode = "400", description = "Invalid create profile request.")
|
||||
@ApiResponse(responseCode = "401", description = "Account authentication check failed.")
|
||||
@ApiResponse(responseCode = "403", description = "The request contained a payment address, but payments are not supported in the region of the account’s phone number.")
|
||||
@ApiResponse(responseCode = "412", description = "The requesting account has the profiles_v2 capability")
|
||||
@ApiResponse(responseCode = "422", description = "Invalid request format")
|
||||
public Response setProfile(@Auth AuthenticatedDevice auth, @NotNull @Valid CreateProfileRequest request) {
|
||||
|
||||
final Account account = accountsManager.getByAccountIdentifier(auth.accountIdentifier())
|
||||
@@ -214,8 +229,16 @@ public class ProfileController {
|
||||
}
|
||||
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/{identifier}/{version}")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Operation(
|
||||
summary = "Get versioned profile",
|
||||
description = "Retrieves a specific version of an account's profile. Requires either authentication or an unidentified access key.")
|
||||
@ApiResponse(responseCode = "200", description = "Profile retrieved successfully.", useReturnTypeSchema = true)
|
||||
@ApiResponse(responseCode = "400", description = "Malformed identifier")
|
||||
@ApiResponse(responseCode = "401", description = "Not authorized to access this profile.")
|
||||
@ApiResponse(responseCode = "404", description = "Profile or account not found.")
|
||||
@ApiResponse(responseCode = "429", description = "Rate limit exceeded.")
|
||||
@ManagedAsync
|
||||
public VersionedProfileResponse getProfile(
|
||||
@Auth Optional<AuthenticatedDevice> maybeAuthenticatedDevice,
|
||||
@@ -241,9 +264,21 @@ public class ProfileController {
|
||||
}
|
||||
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/{identifier}/{version}/{credentialRequest}")
|
||||
public CredentialProfileResponse getProfile(
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Operation(
|
||||
summary = "Get profile with credential",
|
||||
description = "Retrieves a specific version of an account's profile along with an expiring profile key credential. Requires either authentication or an unidentified access key."
|
||||
)
|
||||
@ApiResponse(
|
||||
responseCode = "200",
|
||||
description = "Account found. Profile information will be limited and credential will be null if the version was not found",
|
||||
useReturnTypeSchema = true)
|
||||
@ApiResponse(responseCode = "400", description = "Invalid credential type or credential request.")
|
||||
@ApiResponse(responseCode = "401", description = "Not authorized to access this profile.")
|
||||
@ApiResponse(responseCode = "404", description = "Profile or account not found.")
|
||||
@ApiResponse(responseCode = "429", description = "Rate limit exceeded.")
|
||||
public ExpiringProfileKeyCredentialProfileResponse getProfile(
|
||||
@Auth Optional<AuthenticatedDevice> maybeAuthenticatedDevice,
|
||||
@HeaderParam(HeaderUtils.UNIDENTIFIED_ACCESS_KEY) Optional<Anonymous> accessKey,
|
||||
@Context ContainerRequestContext containerRequestContext,
|
||||
@@ -276,8 +311,16 @@ 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).
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/{identifier}")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Operation(
|
||||
summary = "Get unversioned profile",
|
||||
description = "Retrieves basic profile information without a specific version. Supports ACI and PNI identifiers. Requires authentication, an unidentified access key, or a group send token.")
|
||||
@ApiResponse(responseCode = "200", description = "Unversioned profile retrieved successfully.", useReturnTypeSchema = true)
|
||||
@ApiResponse(responseCode = "400", description = "Invalid request (e.g., multiple authorization types provided).")
|
||||
@ApiResponse(responseCode = "401", description = "Not authorized to access this profile.")
|
||||
@ApiResponse(responseCode = "404", description = "Account not found.")
|
||||
@ApiResponse(responseCode = "429", description = "Rate limit exceeded.")
|
||||
@ManagedAsync
|
||||
public BaseProfileResponse getUnversionedProfile(
|
||||
@Auth Optional<AuthenticatedDevice> maybeAuthenticatedDevice,
|
||||
@@ -318,9 +361,17 @@ public class ProfileController {
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/identity_check/batch")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/identity_check/batch")
|
||||
@Operation(
|
||||
summary = "Batch identity key check",
|
||||
description = "Checks identity key fingerprints for multiple accounts. Returns accounts where the fingerprint does not match. Should not be authenticated.")
|
||||
@ApiResponse(
|
||||
responseCode = "200",
|
||||
description = "Batch check completed successfully. Response may contain accounts with mismatched fingerprints.",
|
||||
content = @Content(schema = @Schema(implementation = BatchIdentityCheckResponse.class)))
|
||||
@ApiResponse(responseCode = "400", description = "Invalid request format or validation failed.")
|
||||
public CompletableFuture<BatchIdentityCheckResponse> runBatchIdentityCheck(@NotNull @Valid BatchIdentityCheckRequest request) {
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
List<BatchIdentityCheckResponse.Element> responseElements = Collections.synchronizedList(new ArrayList<>());
|
||||
@@ -383,18 +434,25 @@ public class ProfileController {
|
||||
final boolean isSelf,
|
||||
final ContainerRequestContext containerRequestContext) {
|
||||
|
||||
final ExpiringProfileKeyCredentialResponse expiringProfileKeyCredentialResponse = profilesManager.get(account.getUuid(), version)
|
||||
.map(profile -> {
|
||||
final ExpiringProfileKeyCredentialResponse profileKeyCredentialResponse;
|
||||
try {
|
||||
profileKeyCredentialResponse = ProfileHelper.getExpiringProfileKeyCredential(HexFormat.of().parseHex(encodedCredentialRequest),
|
||||
profile, new ServiceId.Aci(account.getUuid()), zkProfileOperations);
|
||||
} catch (VerificationFailedException | InvalidInputException e) {
|
||||
throw new BadRequestException(e);
|
||||
}
|
||||
return profileKeyCredentialResponse;
|
||||
})
|
||||
.orElse(null);
|
||||
final ExpiringProfileKeyCredentialResponse expiringProfileKeyCredentialResponse;
|
||||
|
||||
if (account.getCurrentProfileVersion().map(version::equals).orElse(false)) {
|
||||
expiringProfileKeyCredentialResponse = profilesManager.get(account.getUuid(), version)
|
||||
.map(profile -> {
|
||||
final ExpiringProfileKeyCredentialResponse profileKeyCredentialResponse;
|
||||
try {
|
||||
profileKeyCredentialResponse = ProfileHelper.getExpiringProfileKeyCredential(
|
||||
HexFormat.of().parseHex(encodedCredentialRequest),
|
||||
profile, new ServiceId.Aci(account.getUuid()), zkProfileOperations);
|
||||
} catch (VerificationFailedException | InvalidInputException e) {
|
||||
throw new BadRequestException(e);
|
||||
}
|
||||
return profileKeyCredentialResponse;
|
||||
})
|
||||
.orElse(null);
|
||||
} else {
|
||||
expiringProfileKeyCredentialResponse = null;
|
||||
}
|
||||
|
||||
return new ExpiringProfileKeyCredentialProfileResponse(
|
||||
buildVersionedProfileResponse(account, version, isSelf, true, containerRequestContext),
|
||||
@@ -410,7 +468,7 @@ public class ProfileController {
|
||||
final Optional<VersionedProfile> maybeProfile = profilesManager.get(account.getUuid(), version);
|
||||
|
||||
if (maybeProfile.isEmpty()) {
|
||||
// Hypothesis: this should basically never happen since clients can't delete versions
|
||||
// this can happen if an account re-registers, which includes some device-transfer scenarios
|
||||
Metrics.counter(
|
||||
VERSION_NOT_FOUND_COUNTER_NAME,
|
||||
Tags.of(
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
|
||||
/// Helper methods to centrally define rate-limit key formats used in multiple places
|
||||
public class RateLimitKeys {
|
||||
|
||||
/// Key for rate-limiting a device's pre-keys
|
||||
///
|
||||
/// @param sourceAci the account identifier of the authenticated device fetching the pre-keys
|
||||
/// @param sourceDeviceId the deviceId of the authenticated device fetching pre-keys
|
||||
/// @param targetIdentifier the [ServiceIdentifier] of the target account
|
||||
/// @param targetDeviceId the deviceId of the target device, empty if fetching all device pre-keys
|
||||
/// @param targetRegistrationId the registrationId of the target device, empty if fetching all device pre-keys
|
||||
/// @return the rate-limit key
|
||||
public static String preKeyLimiterKey(
|
||||
final UUID sourceAci,
|
||||
final byte sourceDeviceId,
|
||||
final ServiceIdentifier targetIdentifier,
|
||||
final Optional<Byte> targetDeviceId,
|
||||
final Optional<Integer> targetRegistrationId) {
|
||||
return String.format("%s.%s__%s.%s.%s",
|
||||
sourceAci,
|
||||
sourceDeviceId,
|
||||
targetIdentifier.uuid(),
|
||||
targetDeviceId.map(String::valueOf).orElse("*"),
|
||||
targetRegistrationId.map(String::valueOf).orElse("*"));
|
||||
}
|
||||
}
|
||||
+20
-4
@@ -34,6 +34,8 @@ import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Optional;
|
||||
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;
|
||||
@@ -44,6 +46,7 @@ import org.whispersystems.textsecuregcm.entities.RegistrationLockFailure;
|
||||
import org.whispersystems.textsecuregcm.entities.RegistrationRequest;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.spam.RegistrationFraudChecker;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
|
||||
@@ -69,16 +72,21 @@ public class RegistrationController {
|
||||
private final PhoneVerificationTokenManager phoneVerificationTokenManager;
|
||||
private final RegistrationLockVerificationManager registrationLockVerificationManager;
|
||||
private final RateLimiters rateLimiters;
|
||||
private final RegistrationFraudChecker registrationFraudChecker;
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(RegistrationController.class);
|
||||
|
||||
public RegistrationController(final AccountsManager accounts,
|
||||
final PhoneVerificationTokenManager phoneVerificationTokenManager,
|
||||
final RegistrationLockVerificationManager registrationLockVerificationManager,
|
||||
final RateLimiters rateLimiters) {
|
||||
final RateLimiters rateLimiters,
|
||||
final RegistrationFraudChecker registrationFraudChecker) {
|
||||
|
||||
this.accounts = accounts;
|
||||
this.phoneVerificationTokenManager = phoneVerificationTokenManager;
|
||||
this.registrationLockVerificationManager = registrationLockVerificationManager;
|
||||
this.rateLimiters = rateLimiters;
|
||||
this.registrationFraudChecker = registrationFraudChecker;
|
||||
}
|
||||
|
||||
@POST
|
||||
@@ -118,15 +126,15 @@ public class RegistrationController {
|
||||
|
||||
if (!(registrationRequest.accountAttributes().getCapabilities() != null
|
||||
? registrationRequest.accountAttributes().getCapabilities()
|
||||
: Collections.<DeviceCapability>emptySet()).containsAll(DeviceCapability.CAPABILITIES_REQUIRED_FOR_REGISTRATION)) {
|
||||
: Collections.<DeviceCapability>emptySet()).containsAll(DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES)) {
|
||||
|
||||
throw new WebApplicationException("Missing required device capability", 499);
|
||||
}
|
||||
|
||||
rateLimiters.getRegistrationLimiter().validate(number);
|
||||
|
||||
final PhoneVerificationRequest.VerificationType verificationType = phoneVerificationTokenManager.verify(
|
||||
requestContext, number, registrationRequest);
|
||||
final PhoneVerificationRequest.VerificationType verificationType =
|
||||
phoneVerificationTokenManager.verify(requestContext, number, registrationRequest);
|
||||
|
||||
final Optional<Account> existingAccount = accounts.getByE164(number);
|
||||
|
||||
@@ -169,6 +177,14 @@ public class RegistrationController {
|
||||
registrationRequest.deviceActivationRequest().pniPqLastResortPreKey()),
|
||||
userAgent);
|
||||
|
||||
if (verificationType == PhoneVerificationRequest.VerificationType.SESSION) {
|
||||
try {
|
||||
registrationFraudChecker.handleVerificationCompleted(registrationRequest.sessionId(), account);
|
||||
} catch (final Exception e) {
|
||||
logger.warn("Failed to notify fraud checker of completed verification session", e);
|
||||
}
|
||||
}
|
||||
|
||||
Metrics.counter(ACCOUNT_CREATED_COUNTER_NAME, Tags.of(UserAgentTagUtil.getPlatformTag(userAgent),
|
||||
Tag.of(COUNTRY_CODE_TAG_NAME, Util.getCountryCode(number)),
|
||||
Tag.of(REGION_CODE_TAG_NAME, Util.getRegion(number)),
|
||||
|
||||
+9
-1
@@ -782,6 +782,10 @@ public class VerificationController {
|
||||
|
||||
boolean existingRRP = false;
|
||||
if (resultSession.verified()) {
|
||||
// Since there is a valid verification session we invalidate the other possible verification mechanism,
|
||||
// the RRP. It's possible the client will not actually be able to register (e.g. failed reglock challenge), and
|
||||
// so we will have removed the RRP unnecessarily. The impact of this is low, since the owner of the RRP
|
||||
// can always just fallback to session-based verification.
|
||||
existingRRP = registrationRecoveryPasswordsManager.remove(phoneNumberIdentifiers.getPhoneNumberIdentifier(registrationServiceSession.number()).join()).join();
|
||||
}
|
||||
|
||||
@@ -854,7 +858,11 @@ public class VerificationController {
|
||||
.orElseThrow(NotFoundException::new);
|
||||
|
||||
if (registrationServiceSession.verified()) {
|
||||
registrationRecoveryPasswordsManager.remove(phoneNumberIdentifiers.getPhoneNumberIdentifier(registrationServiceSession.number()).join());
|
||||
// Since there is a valid verification session we invalidate the other possible verification mechanism,
|
||||
// the RRP. It's possible the client will not actually be able to register (e.g. failed reglock challenge), and
|
||||
// so we will have removed the RRP unnecessarily. The impact of this is low, since the owner of the RRP
|
||||
// can always just fallback to session-based verification.
|
||||
registrationRecoveryPasswordsManager.remove(phoneNumberIdentifiers.getPhoneNumberIdentifier(registrationServiceSession.number()).join()).join();
|
||||
}
|
||||
|
||||
return registrationServiceSession;
|
||||
|
||||
+8
@@ -8,6 +8,7 @@ package org.whispersystems.textsecuregcm.entities;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.util.ByteArrayBase64WithPaddingAdapter;
|
||||
@@ -17,27 +18,34 @@ import org.whispersystems.textsecuregcm.util.IdentityKeyAdapter;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Schema(description = "Unversioned profile containing basic information")
|
||||
public class BaseProfileResponse {
|
||||
|
||||
@Schema(description = "The account's public identity key (unpadded base64)")
|
||||
@JsonProperty
|
||||
@JsonSerialize(using = IdentityKeyAdapter.Serializer.class)
|
||||
@JsonDeserialize(using = IdentityKeyAdapter.Deserializer.class)
|
||||
private IdentityKey identityKey;
|
||||
|
||||
@Schema(description = "Checksum for unidentified access authentication (padded base64)")
|
||||
@JsonProperty
|
||||
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
|
||||
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
|
||||
private byte[] unidentifiedAccess;
|
||||
|
||||
@Schema(description = "Whether unidentified access is unrestricted for this account")
|
||||
@JsonProperty
|
||||
private boolean unrestrictedUnidentifiedAccess;
|
||||
|
||||
@Schema(description = "Device capabilities and whether they are enabled")
|
||||
@JsonProperty
|
||||
private Map<String, Boolean> capabilities;
|
||||
|
||||
@Schema(description = "List of badges displayed on the profile")
|
||||
@JsonProperty
|
||||
private List<Badge> badges;
|
||||
|
||||
@Schema(description = "Service identifier (ACI or PNI)")
|
||||
@JsonProperty
|
||||
@JsonSerialize(using = ServiceIdentifierAdapter.ServiceIdentifierSerializer.class)
|
||||
@JsonDeserialize(using = ServiceIdentifierAdapter.ServiceIdentifierDeserializer.class)
|
||||
|
||||
+18
-11
@@ -7,29 +7,36 @@ package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import java.util.List;
|
||||
import javax.annotation.Nullable;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import java.util.List;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.util.ExactlySize;
|
||||
import org.whispersystems.textsecuregcm.util.ServiceIdentifierAdapter;
|
||||
|
||||
public record BatchIdentityCheckRequest(@Valid @NotNull @Size(max = 1000) List<Element> elements) {
|
||||
@Schema(description = "Request to check identity key fingerprints for multiple accounts")
|
||||
public record BatchIdentityCheckRequest(
|
||||
@Schema(description = "List of accounts to check")
|
||||
@Valid @NotNull @Size(max = 1000) List<Element> elements) {
|
||||
|
||||
/**
|
||||
* @param uuid account id or phone number id
|
||||
* @param fingerprint most significant 4 bytes of SHA-256 of the 33-byte identity key field (32-byte curve25519 public
|
||||
* key prefixed with 0x05)
|
||||
*/
|
||||
public record Element(@NotNull
|
||||
@JsonSerialize(using = ServiceIdentifierAdapter.ServiceIdentifierSerializer.class)
|
||||
@JsonDeserialize(using = ServiceIdentifierAdapter.ServiceIdentifierDeserializer.class)
|
||||
ServiceIdentifier uuid,
|
||||
@Schema(description = "A service identifier and expected identity key fingerprint")
|
||||
public record Element(
|
||||
@Schema(description = "Identifier (ACI or PNI)")
|
||||
@NotNull
|
||||
@JsonSerialize(using = ServiceIdentifierAdapter.ServiceIdentifierSerializer.class)
|
||||
@JsonDeserialize(using = ServiceIdentifierAdapter.ServiceIdentifierDeserializer.class)
|
||||
ServiceIdentifier uuid,
|
||||
|
||||
@NotNull
|
||||
@ExactlySize(4)
|
||||
byte[] fingerprint) {
|
||||
}
|
||||
@Schema(description = "Expected identity key fingerprint (4 bytes, most significant bytes of SHA-256 hash of 33-byte identity key field)")
|
||||
@NotNull
|
||||
@ExactlySize(4)
|
||||
byte[] fingerprint) {
|
||||
}
|
||||
}
|
||||
+18
-10
@@ -8,6 +8,7 @@ package org.whispersystems.textsecuregcm.entities;
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import java.util.List;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
@@ -16,17 +17,24 @@ import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.util.IdentityKeyAdapter;
|
||||
import org.whispersystems.textsecuregcm.util.ServiceIdentifierAdapter;
|
||||
|
||||
public record BatchIdentityCheckResponse(@Valid List<Element> elements) {
|
||||
@Schema(description = "Response containing accounts with mismatched identity key fingerprints")
|
||||
public record BatchIdentityCheckResponse(
|
||||
@Schema(description = "List of accounts where fingerprint did not match (empty if all matched)")
|
||||
@Valid List<Element> elements) {
|
||||
|
||||
public record Element(@JsonInclude(JsonInclude.Include.NON_EMPTY)
|
||||
@JsonSerialize(using = ServiceIdentifierAdapter.ServiceIdentifierSerializer.class)
|
||||
@JsonDeserialize(using = ServiceIdentifierAdapter.ServiceIdentifierDeserializer.class)
|
||||
@NotNull
|
||||
ServiceIdentifier uuid,
|
||||
@Schema(description = "An account with a mismatched identity key fingerprint")
|
||||
public record Element(
|
||||
@Schema(description = "Service identifier (ACI or PNI)")
|
||||
@JsonInclude(JsonInclude.Include.NON_EMPTY)
|
||||
@JsonSerialize(using = ServiceIdentifierAdapter.ServiceIdentifierSerializer.class)
|
||||
@JsonDeserialize(using = ServiceIdentifierAdapter.ServiceIdentifierDeserializer.class)
|
||||
@NotNull
|
||||
ServiceIdentifier uuid,
|
||||
|
||||
@NotNull
|
||||
@JsonSerialize(using = IdentityKeyAdapter.Serializer.class)
|
||||
@JsonDeserialize(using = IdentityKeyAdapter.Deserializer.class)
|
||||
IdentityKey identityKey) {
|
||||
@Schema(description = "The actual identity key for this account")
|
||||
@NotNull
|
||||
@JsonSerialize(using = IdentityKeyAdapter.Serializer.class)
|
||||
@JsonDeserialize(using = IdentityKeyAdapter.Deserializer.class)
|
||||
IdentityKey identityKey) {
|
||||
}
|
||||
}
|
||||
+12
@@ -8,6 +8,7 @@ package org.whispersystems.textsecuregcm.entities;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
@@ -17,52 +18,63 @@ import org.whispersystems.textsecuregcm.util.ByteArrayBase64WithPaddingAdapter;
|
||||
import org.whispersystems.textsecuregcm.util.ExactlySize;
|
||||
import org.whispersystems.textsecuregcm.util.ValidHexString;
|
||||
|
||||
@Schema(description = "Request to create or update a versioned profile")
|
||||
public record CreateProfileRequest(
|
||||
@Schema(description = "Profile key commitment")
|
||||
@JsonProperty
|
||||
@NotNull
|
||||
@JsonDeserialize(using = ProfileKeyCommitmentAdapter.Deserializing.class)
|
||||
@JsonSerialize(using = ProfileKeyCommitmentAdapter.Serializing.class)
|
||||
ProfileKeyCommitment commitment,
|
||||
|
||||
@Schema(description = "Profile version identifier (hex-encoding of the public key)")
|
||||
@JsonProperty
|
||||
@NotEmpty
|
||||
@ValidHexString
|
||||
@ExactlySize({64})
|
||||
String version,
|
||||
|
||||
@Schema(description = "Encrypted profile name. Padded base64.")
|
||||
@JsonProperty
|
||||
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
|
||||
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
|
||||
@ExactlySize({81, 285})
|
||||
byte[] name,
|
||||
|
||||
@Schema(description = "Encrypted about emoji. Padded base64.")
|
||||
@JsonProperty
|
||||
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
|
||||
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
|
||||
@ExactlySize({0, 60})
|
||||
byte[] aboutEmoji,
|
||||
|
||||
@Schema(description = "Encrypted about text. Padded base64.")
|
||||
@JsonProperty
|
||||
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
|
||||
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
|
||||
@ExactlySize({0, 156, 282, 540})
|
||||
byte[] about,
|
||||
|
||||
@Schema(description = "Encrypted payment address. Padded base64.")
|
||||
@JsonProperty
|
||||
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
|
||||
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
|
||||
@ExactlySize({0, 582})
|
||||
byte[] paymentAddress,
|
||||
|
||||
@Schema(description = "Whether the profile has an avatar")
|
||||
@JsonProperty("avatar")
|
||||
boolean hasAvatar,
|
||||
|
||||
@Schema(description = "Whether the avatar is unchanged from the previous version")
|
||||
@JsonProperty
|
||||
boolean sameAvatar,
|
||||
|
||||
@Schema(description = "List of badge IDs to display on the profile")
|
||||
@JsonProperty("badgeIds")
|
||||
Optional<List<String>> badges,
|
||||
|
||||
@Schema(description = "Encrypted phone number sharing preference. Padded base64.")
|
||||
@JsonProperty
|
||||
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
|
||||
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
|
||||
|
||||
-25
@@ -1,25 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2021 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonUnwrapped;
|
||||
|
||||
public abstract class CredentialProfileResponse {
|
||||
|
||||
@JsonUnwrapped
|
||||
private VersionedProfileResponse versionedProfileResponse;
|
||||
|
||||
protected CredentialProfileResponse() {
|
||||
}
|
||||
|
||||
protected CredentialProfileResponse(final VersionedProfileResponse versionedProfileResponse) {
|
||||
this.versionedProfileResponse = versionedProfileResponse;
|
||||
}
|
||||
|
||||
public VersionedProfileResponse getVersionedProfileResponse() {
|
||||
return versionedProfileResponse;
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,10 @@ package org.whispersystems.textsecuregcm.entities;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.constraints.Max;
|
||||
import jakarta.validation.constraints.Min;
|
||||
import org.signal.libsignal.protocol.ecc.ECPublicKey;
|
||||
import org.whispersystems.textsecuregcm.storage.KeyIdUtil;
|
||||
import org.whispersystems.textsecuregcm.util.ECPublicKeyAdapter;
|
||||
|
||||
public record ECPreKey(
|
||||
@@ -16,6 +19,8 @@ public record ECPreKey(
|
||||
An arbitrary ID for this key, which will be provided by peers using this key to encrypt messages so the private key can be looked up.
|
||||
Should not be zero. Should be less than 2^24.
|
||||
""")
|
||||
@Max(KeyIdUtil.MAX_KEY_ID)
|
||||
@Min(KeyIdUtil.MIN_KEY_ID)
|
||||
long keyId,
|
||||
|
||||
@JsonSerialize(using = ECPublicKeyAdapter.Serializer.class)
|
||||
|
||||
@@ -8,7 +8,10 @@ package org.whispersystems.textsecuregcm.entities;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.constraints.Max;
|
||||
import jakarta.validation.constraints.Min;
|
||||
import org.signal.libsignal.protocol.ecc.ECPublicKey;
|
||||
import org.whispersystems.textsecuregcm.storage.KeyIdUtil;
|
||||
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
|
||||
import org.whispersystems.textsecuregcm.util.ECPublicKeyAdapter;
|
||||
import java.util.Arrays;
|
||||
@@ -19,6 +22,8 @@ public record ECSignedPreKey(
|
||||
An arbitrary ID for this key, which will be provided by peers using this key to encrypt messages so the private key can be looked up.
|
||||
Should not be zero. Should be less than 2^24.
|
||||
""")
|
||||
@Max(KeyIdUtil.MAX_KEY_ID)
|
||||
@Min(KeyIdUtil.MIN_KEY_ID)
|
||||
long keyId,
|
||||
|
||||
@JsonSerialize(using = ECPublicKeyAdapter.Serializer.class)
|
||||
|
||||
+13
-2
@@ -6,13 +6,20 @@
|
||||
package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.annotation.JsonUnwrapped;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import javax.annotation.Nullable;
|
||||
import org.signal.libsignal.zkgroup.profiles.ExpiringProfileKeyCredentialResponse;
|
||||
|
||||
public class ExpiringProfileKeyCredentialProfileResponse extends CredentialProfileResponse {
|
||||
@Schema(description = "Profile response with an expiring profile key credential")
|
||||
public class ExpiringProfileKeyCredentialProfileResponse {
|
||||
|
||||
@JsonUnwrapped
|
||||
private VersionedProfileResponse versionedProfileResponse;
|
||||
|
||||
@Schema(description = "Expiring profile key credential response. Null if profile version was not found or if the profile version is not current")
|
||||
@JsonProperty
|
||||
@JsonSerialize(using = ExpiringProfileKeyCredentialResponseAdapter.Serializing.class)
|
||||
@JsonDeserialize(using = ExpiringProfileKeyCredentialResponseAdapter.Deserializing.class)
|
||||
@@ -25,7 +32,7 @@ public class ExpiringProfileKeyCredentialProfileResponse extends CredentialProfi
|
||||
public ExpiringProfileKeyCredentialProfileResponse(final VersionedProfileResponse versionedProfileResponse,
|
||||
@Nullable final ExpiringProfileKeyCredentialResponse credential) {
|
||||
|
||||
super(versionedProfileResponse);
|
||||
this.versionedProfileResponse = versionedProfileResponse;
|
||||
this.credential = credential;
|
||||
}
|
||||
|
||||
@@ -33,4 +40,8 @@ public class ExpiringProfileKeyCredentialProfileResponse extends CredentialProfi
|
||||
public ExpiringProfileKeyCredentialResponse getCredential() {
|
||||
return credential;
|
||||
}
|
||||
|
||||
public VersionedProfileResponse getVersionedProfileResponse() {
|
||||
return versionedProfileResponse;
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,10 @@ package org.whispersystems.textsecuregcm.entities;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.constraints.Max;
|
||||
import jakarta.validation.constraints.Min;
|
||||
import org.signal.libsignal.protocol.kem.KEMPublicKey;
|
||||
import org.whispersystems.textsecuregcm.storage.KeyIdUtil;
|
||||
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
|
||||
import org.whispersystems.textsecuregcm.util.KEMPublicKeyAdapter;
|
||||
import java.util.Arrays;
|
||||
@@ -20,6 +23,8 @@ public record KEMSignedPreKey(
|
||||
Should not be zero. Should be less than 2^24. The owner of this key must be able to determine from the key ID whether this represents
|
||||
a single-use or last-resort key, but another party should *not* be able to tell.
|
||||
""")
|
||||
@Max(KeyIdUtil.MAX_KEY_ID)
|
||||
@Min(KeyIdUtil.MIN_KEY_ID)
|
||||
long keyId,
|
||||
|
||||
@JsonSerialize(using = KEMPublicKeyAdapter.Serializer.class)
|
||||
|
||||
+18
-11
@@ -6,44 +6,51 @@
|
||||
package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
|
||||
@Schema(description = "Profile avatar upload form (S3 Post Policy, AWS Signature version 4)")
|
||||
public class ProfileAvatarUploadAttributes {
|
||||
|
||||
@Schema(description = "Object key for the avatar")
|
||||
@JsonProperty
|
||||
private String key;
|
||||
|
||||
@Schema(description = "Credential for the upload")
|
||||
@JsonProperty
|
||||
private String credential;
|
||||
|
||||
@Schema(description = "Access control list setting")
|
||||
@JsonProperty
|
||||
private String acl;
|
||||
|
||||
@Schema(description = "Signing algorithm")
|
||||
@JsonProperty
|
||||
private String algorithm;
|
||||
|
||||
@Schema(description = "Date in AWS format")
|
||||
@JsonProperty
|
||||
private String date;
|
||||
|
||||
@Schema(description = "Base64-encoded upload policy")
|
||||
@JsonProperty
|
||||
private String policy;
|
||||
|
||||
@Schema(description = "Signature calculated over the policy")
|
||||
@JsonProperty
|
||||
private String signature;
|
||||
|
||||
public ProfileAvatarUploadAttributes() {}
|
||||
|
||||
public ProfileAvatarUploadAttributes(String key, String credential,
|
||||
String acl, String algorithm,
|
||||
String date, String policy,
|
||||
String signature)
|
||||
{
|
||||
this.key = key;
|
||||
public ProfileAvatarUploadAttributes(String key, String credential, String acl, String algorithm, String date,
|
||||
String policy, String signature) {
|
||||
|
||||
this.key = key;
|
||||
this.credential = credential;
|
||||
this.acl = acl;
|
||||
this.algorithm = algorithm;
|
||||
this.date = date;
|
||||
this.policy = policy;
|
||||
this.signature = signature;
|
||||
this.acl = acl;
|
||||
this.algorithm = algorithm;
|
||||
this.date = date;
|
||||
this.policy = policy;
|
||||
this.signature = signature;
|
||||
}
|
||||
|
||||
public String getKey() {
|
||||
|
||||
+9
@@ -9,36 +9,45 @@ import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.annotation.JsonUnwrapped;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import org.whispersystems.textsecuregcm.util.ByteArrayBase64WithPaddingAdapter;
|
||||
|
||||
@Schema(description = "Versioned profile containing encrypted fields. Versioned fields may be empty if the version was not found.")
|
||||
public record VersionedProfileResponse(
|
||||
|
||||
@Schema(description = "Base profile information")
|
||||
@JsonUnwrapped
|
||||
BaseProfileResponse baseProfileResponse,
|
||||
|
||||
@Schema(description = "Encrypted profile name. Padded base64.")
|
||||
@JsonProperty
|
||||
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
|
||||
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
|
||||
byte[] name,
|
||||
|
||||
@Schema(description = "Encrypted about text. Padded base64.")
|
||||
@JsonProperty
|
||||
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
|
||||
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
|
||||
byte[] about,
|
||||
|
||||
@Schema(description = "Encrypted about emoji. Padded base64.")
|
||||
@JsonProperty
|
||||
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
|
||||
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
|
||||
byte[] aboutEmoji,
|
||||
|
||||
@Schema(description = "Avatar CDN path")
|
||||
@JsonProperty
|
||||
String avatar,
|
||||
|
||||
@Schema(description = "Encrypted payment address. Padded base64.")
|
||||
@JsonProperty
|
||||
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
|
||||
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
|
||||
byte[] paymentAddress,
|
||||
|
||||
@Schema(description = "Encrypted phone number sharing preference. Padded base64.")
|
||||
@JsonProperty
|
||||
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
|
||||
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
|
||||
|
||||
+64
-18
@@ -7,6 +7,7 @@ package org.whispersystems.textsecuregcm.filters;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.common.net.HttpHeaders;
|
||||
import com.vdurmont.semver4j.Semver;
|
||||
import io.grpc.Metadata;
|
||||
@@ -23,14 +24,21 @@ import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import javax.annotation.Nullable;
|
||||
import org.whispersystems.textsecuregcm.auth.AccountAuthenticator;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.RequireAuthenticationInterceptor;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicRemoteDeprecationConfiguration;
|
||||
import org.whispersystems.textsecuregcm.grpc.GrpcExceptions;
|
||||
import org.whispersystems.textsecuregcm.grpc.RequestAttributesUtil;
|
||||
import org.whispersystems.textsecuregcm.grpc.ServerInterceptorUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.util.HeaderUtils;
|
||||
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
|
||||
import org.whispersystems.textsecuregcm.util.ua.UnrecognizedUserAgentException;
|
||||
import org.whispersystems.textsecuregcm.util.ua.UserAgent;
|
||||
@@ -44,6 +52,8 @@ import org.whispersystems.textsecuregcm.util.ua.UserAgentUtil;
|
||||
*/
|
||||
public class RemoteDeprecationFilter implements Filter, ServerInterceptor {
|
||||
|
||||
private final AccountsManager accountsManager;
|
||||
private final AccountAuthenticator accountAuthenticator;
|
||||
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
|
||||
|
||||
private static final String DEPRECATED_CLIENT_COUNTER_NAME = name(RemoteDeprecationFilter.class, "deprecated");
|
||||
@@ -52,9 +62,14 @@ public class RemoteDeprecationFilter implements Filter, ServerInterceptor {
|
||||
private static final String REASON_TAG_NAME = "reason";
|
||||
private static final String EXPIRED_CLIENT_REASON = "expired";
|
||||
private static final String BLOCKED_CLIENT_REASON = "blocked";
|
||||
private static final String UNRECOGNIZED_UA_REASON = "unrecognized_user_agent";
|
||||
private static final String SPQR_NOT_SUPPORTED_REASON = "spqr";
|
||||
|
||||
public RemoteDeprecationFilter(final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
|
||||
public RemoteDeprecationFilter(final AccountsManager accountsManager,
|
||||
final AccountAuthenticator accountAuthenticator,
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
|
||||
|
||||
this.accountsManager = accountsManager;
|
||||
this.accountAuthenticator = accountAuthenticator;
|
||||
this.dynamicConfigurationManager = dynamicConfigurationManager;
|
||||
}
|
||||
|
||||
@@ -69,7 +84,7 @@ public class RemoteDeprecationFilter implements Filter, ServerInterceptor {
|
||||
userAgent = null;
|
||||
}
|
||||
|
||||
if (shouldBlock(userAgent)) {
|
||||
if (shouldBlock(userAgent, ((HttpServletRequest) request).getHeader(HttpHeaders.AUTHORIZATION))) {
|
||||
((HttpServletResponse) response).sendError(499);
|
||||
} else {
|
||||
chain.doFilter(request, response);
|
||||
@@ -91,32 +106,41 @@ public class RemoteDeprecationFilter implements Filter, ServerInterceptor {
|
||||
}
|
||||
}).orElse(null);
|
||||
|
||||
if (shouldBlock(userAgent)) {
|
||||
if (shouldBlock(userAgent, headers.get(RequireAuthenticationInterceptor.AUTHORIZATION_METADATA_KEY))) {
|
||||
return ServerInterceptorUtil.closeWithStatusException(call, GrpcExceptions.upgradeRequired());
|
||||
} else {
|
||||
return next.startCall(call, headers);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean shouldBlock(@Nullable final UserAgent userAgent) {
|
||||
@VisibleForTesting
|
||||
boolean shouldBlock(@Nullable final UserAgent userAgent, @Nullable final String authHeader) {
|
||||
|
||||
final DynamicRemoteDeprecationConfiguration configuration = dynamicConfigurationManager
|
||||
.getConfiguration().getRemoteDeprecationConfiguration();
|
||||
final Map<ClientPlatform, Semver> minimumVersionsByPlatform = configuration.getMinimumVersions();
|
||||
final Map<ClientPlatform, Semver> minimumVersionsByPlatform = configuration.minimumVersions();
|
||||
final Map<ClientPlatform, Semver> versionsPendingDeprecationByPlatform = configuration
|
||||
.getVersionsPendingDeprecation();
|
||||
final Map<ClientPlatform, Set<Semver>> blockedVersionsByPlatform = configuration.getBlockedVersions();
|
||||
final Map<ClientPlatform, Set<Semver>> versionsPendingBlockByPlatform = configuration.getVersionsPendingBlock();
|
||||
|
||||
boolean shouldBlock = false;
|
||||
.versionsPendingDeprecation();
|
||||
final Map<ClientPlatform, Set<Semver>> blockedVersionsByPlatform = configuration.blockedVersions();
|
||||
final Map<ClientPlatform, Set<Semver>> versionsPendingBlockByPlatform = configuration.versionsPendingBlock();
|
||||
|
||||
if (userAgent == null) {
|
||||
if (configuration.isUnrecognizedUserAgentAllowed()) {
|
||||
return false;
|
||||
// In first-party clients, we can enforce SPQR presence via minimum client version. For third-party clients, we
|
||||
// need to do a more expensive check for the actual capability.
|
||||
if ((configuration.spqrEnforcementPending() || configuration.requireSpqr()) && isMissingSpqrCapability(authHeader)) {
|
||||
if (configuration.requireSpqr()) {
|
||||
recordDeprecation(null, SPQR_NOT_SUPPORTED_REASON);
|
||||
return true;
|
||||
}
|
||||
|
||||
recordPendingDeprecation(null, SPQR_NOT_SUPPORTED_REASON);
|
||||
}
|
||||
recordDeprecation(null, UNRECOGNIZED_UA_REASON);
|
||||
return true;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
boolean shouldBlock = false;
|
||||
|
||||
if (blockedVersionsByPlatform.containsKey(userAgent.platform())) {
|
||||
if (blockedVersionsByPlatform.get(userAgent.platform()).contains(userAgent.version())) {
|
||||
recordDeprecation(userAgent, BLOCKED_CLIENT_REASON);
|
||||
@@ -146,15 +170,37 @@ public class RemoteDeprecationFilter implements Filter, ServerInterceptor {
|
||||
return shouldBlock;
|
||||
}
|
||||
|
||||
private void recordDeprecation(final UserAgent userAgent, final String reason) {
|
||||
/// Tests whether the device identified by the given authentication header (if any) is definitively missing the SPQR
|
||||
/// capability.
|
||||
///
|
||||
/// @return `true` if the authenticated device is definitively missing the SPQR capability or `false` if the
|
||||
/// capability is present, no credentials are presented, or if authentication failed for any reason
|
||||
@VisibleForTesting
|
||||
boolean isMissingSpqrCapability(@Nullable final String authHeader) {
|
||||
if (authHeader == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
final Optional<AuthenticatedDevice> maybeAuthenticatedDevice =
|
||||
HeaderUtils.basicCredentialsFromAuthHeader(authHeader)
|
||||
.flatMap(accountAuthenticator::authenticate);
|
||||
|
||||
return maybeAuthenticatedDevice
|
||||
.flatMap(authenticatedDevice -> accountsManager.getByAccountIdentifier(authenticatedDevice.accountIdentifier()))
|
||||
.flatMap(account -> account.getDevice(maybeAuthenticatedDevice.get().deviceId()))
|
||||
.map(device -> !device.hasCapability(DeviceCapability.SPARSE_POST_QUANTUM_RATCHET))
|
||||
.orElse(false);
|
||||
}
|
||||
|
||||
private void recordDeprecation(@Nullable final UserAgent userAgent, final String reason) {
|
||||
Metrics.counter(DEPRECATED_CLIENT_COUNTER_NAME,
|
||||
PLATFORM_TAG, userAgent != null ? userAgent.platform().name().toLowerCase() : "unrecognized",
|
||||
REASON_TAG_NAME, reason).increment();
|
||||
}
|
||||
|
||||
private void recordPendingDeprecation(final UserAgent userAgent, final String reason) {
|
||||
private void recordPendingDeprecation(@Nullable final UserAgent userAgent, final String reason) {
|
||||
Metrics.counter(PENDING_DEPRECATION_COUNTER_NAME,
|
||||
PLATFORM_TAG, userAgent.platform().name().toLowerCase(),
|
||||
PLATFORM_TAG, userAgent != null ? userAgent.platform().name().toLowerCase() : "unrecognized",
|
||||
REASON_TAG_NAME, reason).increment();
|
||||
}
|
||||
}
|
||||
@@ -27,9 +27,9 @@ public class CanonicalRequest {
|
||||
@Nonnull
|
||||
private final String domain;
|
||||
|
||||
private final int maxSizeInBytes;
|
||||
private final long maxSizeInBytes;
|
||||
|
||||
public CanonicalRequest(@Nonnull String canonicalRequest, @Nonnull String resourcePath, @Nonnull String canonicalQuery, @Nonnull String activeDatetime, @Nonnull String credentialScope, @Nonnull String domain, int maxSizeInBytes) {
|
||||
public CanonicalRequest(@Nonnull String canonicalRequest, @Nonnull String resourcePath, @Nonnull String canonicalQuery, @Nonnull String activeDatetime, @Nonnull String credentialScope, @Nonnull String domain, long maxSizeInBytes) {
|
||||
this.canonicalRequest = canonicalRequest;
|
||||
this.resourcePath = resourcePath;
|
||||
this.canonicalQuery = canonicalQuery;
|
||||
@@ -69,7 +69,7 @@ public class CanonicalRequest {
|
||||
return domain;
|
||||
}
|
||||
|
||||
public int getMaxSizeInBytes() {
|
||||
public long getMaxSizeInBytes() {
|
||||
return maxSizeInBytes;
|
||||
}
|
||||
}
|
||||
+4
-7
@@ -26,19 +26,16 @@ public class CanonicalRequestGenerator {
|
||||
@Nonnull
|
||||
private final String email;
|
||||
|
||||
private final int maxSizeBytes;
|
||||
|
||||
@Nonnull
|
||||
private final String pathPrefix;
|
||||
|
||||
public CanonicalRequestGenerator(@Nonnull String domain, @Nonnull String email, int maxSizeBytes, @Nonnull String pathPrefix) {
|
||||
public CanonicalRequestGenerator(@Nonnull String domain, @Nonnull String email, @Nonnull String pathPrefix) {
|
||||
this.domain = domain;
|
||||
this.email = email;
|
||||
this.maxSizeBytes = maxSizeBytes;
|
||||
this.pathPrefix = pathPrefix;
|
||||
}
|
||||
|
||||
public CanonicalRequest createFor(@Nonnull final String key, @Nonnull final ZonedDateTime now) {
|
||||
public CanonicalRequest createFor(@Nonnull final String key, @Nonnull final ZonedDateTime now, final long uploadLength) {
|
||||
final StringBuilder result = new StringBuilder("POST\n");
|
||||
|
||||
final StringBuilder resourcePathBuilder = new StringBuilder();
|
||||
@@ -58,7 +55,7 @@ public class CanonicalRequestGenerator {
|
||||
result.append(canonicalQuery).append('\n');
|
||||
|
||||
result.append("host:").append(domain).append('\n');
|
||||
result.append("x-goog-content-length-range:1,").append(maxSizeBytes).append('\n');
|
||||
result.append("x-goog-content-length-range:1,").append(uploadLength).append('\n');
|
||||
result.append("x-goog-resumable:start\n");
|
||||
result.append('\n');
|
||||
|
||||
@@ -66,7 +63,7 @@ public class CanonicalRequestGenerator {
|
||||
|
||||
result.append("UNSIGNED-PAYLOAD");
|
||||
|
||||
return new CanonicalRequest(result.toString(), resourcePath, canonicalQuery, activeDatetime, makeCredentialScope(now), domain, maxSizeBytes);
|
||||
return new CanonicalRequest(result.toString(), resourcePath, canonicalQuery, activeDatetime, makeCredentialScope(now), domain, uploadLength);
|
||||
}
|
||||
|
||||
private String makeCredentialScope(@Nonnull ZonedDateTime now) {
|
||||
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Map;
|
||||
import org.signal.chat.attachments.GetUploadFormRequest;
|
||||
import org.signal.chat.attachments.GetUploadFormResponse;
|
||||
import org.signal.chat.attachments.SimpleAttachmentsGrpc;
|
||||
import org.signal.chat.common.UploadForm;
|
||||
import org.signal.chat.errors.FailedPrecondition;
|
||||
import org.whispersystems.textsecuregcm.attachments.AttachmentGenerator;
|
||||
import org.whispersystems.textsecuregcm.attachments.AttachmentUtil;
|
||||
import org.whispersystems.textsecuregcm.attachments.GcsAttachmentGenerator;
|
||||
import org.whispersystems.textsecuregcm.attachments.TusAttachmentGenerator;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
|
||||
public class AttachmentsGrpcService extends SimpleAttachmentsGrpc.AttachmentsImplBase {
|
||||
|
||||
private final ExperimentEnrollmentManager experimentEnrollmentManager;
|
||||
private final RateLimiter countRateLimiter;
|
||||
private final RateLimiter bytesRateLimiter;
|
||||
private final long maxUploadLength;
|
||||
private final Map<Integer, AttachmentGenerator> attachmentGenerators;
|
||||
private final SecureRandom secureRandom;
|
||||
|
||||
public AttachmentsGrpcService(
|
||||
final ExperimentEnrollmentManager experimentEnrollmentManager,
|
||||
final RateLimiters rateLimiters,
|
||||
final GcsAttachmentGenerator gcsAttachmentGenerator,
|
||||
final TusAttachmentGenerator tusAttachmentGenerator,
|
||||
final long maxUploadLength) {
|
||||
this.experimentEnrollmentManager = experimentEnrollmentManager;
|
||||
this.countRateLimiter = rateLimiters.getAttachmentLimiter();
|
||||
this.bytesRateLimiter = rateLimiters.getAttachmentBytesLimiter();
|
||||
this.maxUploadLength = maxUploadLength;
|
||||
this.secureRandom = new SecureRandom();
|
||||
this.attachmentGenerators = Map.of(
|
||||
2, gcsAttachmentGenerator,
|
||||
3, tusAttachmentGenerator);
|
||||
}
|
||||
|
||||
@Override
|
||||
public GetUploadFormResponse getUploadForm(final GetUploadFormRequest request) throws RateLimitExceededException {
|
||||
if (request.getUploadLength() > maxUploadLength) {
|
||||
return GetUploadFormResponse.newBuilder()
|
||||
.setExceedsMaxUploadLength(FailedPrecondition.getDefaultInstance())
|
||||
.build();
|
||||
}
|
||||
final AuthenticatedDevice auth = AuthenticationUtil.requireAuthenticatedDevice();
|
||||
|
||||
countRateLimiter.validate(auth.accountIdentifier());
|
||||
try {
|
||||
// Ideally we'd check these two rate limits transactionally and only update them if both permits were acquired.
|
||||
// However, just undoing the first modification if the second one fails is close enough for our purposes
|
||||
bytesRateLimiter.validate(auth.accountIdentifier(), request.getUploadLength());
|
||||
} catch (RateLimitExceededException e) {
|
||||
countRateLimiter.restorePermits(auth.accountIdentifier(), 1);
|
||||
throw e;
|
||||
}
|
||||
|
||||
final String key = AttachmentUtil.generateAttachmentKey(secureRandom);
|
||||
final boolean useCdn3 = this.experimentEnrollmentManager.isEnrolled(auth.accountIdentifier(),
|
||||
AttachmentUtil.CDN3_EXPERIMENT_NAME);
|
||||
final int cdn = useCdn3 ? 3 : 2;
|
||||
final AttachmentGenerator.Descriptor descriptor =
|
||||
this.attachmentGenerators.get(cdn).generateAttachment(key, request.getUploadLength());
|
||||
return GetUploadFormResponse.newBuilder().setUploadForm(UploadForm.newBuilder()
|
||||
.setCdn(cdn)
|
||||
.setKey(key)
|
||||
.putAllHeaders(descriptor.headers())
|
||||
.setSignedUploadLocation(descriptor.signedUploadLocation()))
|
||||
.build();
|
||||
}
|
||||
}
|
||||
+24
-27
@@ -32,6 +32,7 @@ import org.signal.chat.backup.SetPublicKeyRequest;
|
||||
import org.signal.chat.backup.SetPublicKeyResponse;
|
||||
import org.signal.chat.backup.SignedPresentation;
|
||||
import org.signal.chat.backup.SimpleBackupsAnonymousGrpc;
|
||||
import org.signal.chat.common.UploadForm;
|
||||
import org.signal.chat.errors.FailedPrecondition;
|
||||
import org.signal.chat.errors.FailedZkAuthentication;
|
||||
import org.signal.libsignal.protocol.InvalidKeyException;
|
||||
@@ -60,10 +61,12 @@ public class BackupsAnonymousGrpcService extends SimpleBackupsAnonymousGrpc.Back
|
||||
|
||||
private final BackupManager backupManager;
|
||||
private final BackupMetrics backupMetrics;
|
||||
private final long maxAttachmentSize;
|
||||
|
||||
public BackupsAnonymousGrpcService(final BackupManager backupManager, final BackupMetrics backupMetrics) {
|
||||
public BackupsAnonymousGrpcService(final BackupManager backupManager, final BackupMetrics backupMetrics, final long maxAttachmentSize) {
|
||||
this.backupManager = backupManager;
|
||||
this.backupMetrics = backupMetrics;
|
||||
this.maxAttachmentSize = maxAttachmentSize;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -178,35 +181,29 @@ public class BackupsAnonymousGrpcService extends SimpleBackupsAnonymousGrpc.Back
|
||||
.setFailedAuthentication(FailedZkAuthentication.newBuilder().setDescription(e.getMessage()).build())
|
||||
.build();
|
||||
}
|
||||
final GetUploadFormResponse.Builder builder = GetUploadFormResponse.newBuilder();
|
||||
switch (request.getUploadTypeCase()) {
|
||||
case MESSAGES -> {
|
||||
final long uploadLength = request.getMessages().getUploadLength();
|
||||
final boolean oversize = uploadLength > BackupManager.MAX_MESSAGE_BACKUP_OBJECT_SIZE;
|
||||
backupMetrics.updateMessageBackupSizeDistribution(backupUser, oversize, Optional.of(uploadLength));
|
||||
if (oversize) {
|
||||
builder.setExceedsMaxUploadLength(FailedPrecondition.getDefaultInstance());
|
||||
} else {
|
||||
final BackupUploadDescriptor uploadDescriptor = backupManager.createMessageBackupUploadDescriptor(backupUser);
|
||||
builder.setUploadForm(builder.getUploadFormBuilder()
|
||||
.setCdn(uploadDescriptor.cdn())
|
||||
.setKey(uploadDescriptor.key())
|
||||
.setSignedUploadLocation(uploadDescriptor.signedUploadLocation())
|
||||
.putAllHeaders(uploadDescriptor.headers())).build();
|
||||
}
|
||||
final long uploadLength = request.getUploadLength();
|
||||
if (uploadLength > maxAttachmentSize) {
|
||||
if (request.getUploadTypeCase() == GetUploadFormRequest.UploadTypeCase.MESSAGES) {
|
||||
backupMetrics.updateMessageBackupSizeDistribution(backupUser, true, Optional.of(uploadLength));
|
||||
}
|
||||
case MEDIA -> {
|
||||
final BackupUploadDescriptor uploadDescriptor = backupManager.createTemporaryAttachmentUploadDescriptor(
|
||||
backupUser);
|
||||
builder.setUploadForm(builder.getUploadFormBuilder()
|
||||
return GetUploadFormResponse.newBuilder().setExceedsMaxUploadLength(FailedPrecondition.getDefaultInstance()).build();
|
||||
}
|
||||
|
||||
final BackupUploadDescriptor uploadDescriptor = switch (request.getUploadTypeCase()) {
|
||||
case MESSAGES -> {
|
||||
backupMetrics.updateMessageBackupSizeDistribution(backupUser, false, Optional.of(uploadLength));
|
||||
yield backupManager.createMessageBackupUploadDescriptor(backupUser, uploadLength);
|
||||
}
|
||||
case MEDIA -> backupManager.createTemporaryAttachmentUploadDescriptor(backupUser, uploadLength);
|
||||
case UPLOADTYPE_NOT_SET -> throw GrpcExceptions.fieldViolation("upload_type", "Must set upload_type");
|
||||
};
|
||||
return GetUploadFormResponse.newBuilder()
|
||||
.setUploadForm(UploadForm.newBuilder()
|
||||
.setCdn(uploadDescriptor.cdn())
|
||||
.setKey(uploadDescriptor.key())
|
||||
.setSignedUploadLocation(uploadDescriptor.signedUploadLocation())
|
||||
.putAllHeaders(uploadDescriptor.headers())).build();
|
||||
}
|
||||
case UPLOADTYPE_NOT_SET -> throw GrpcExceptions.fieldViolation("upload_type", "Must set upload_type");
|
||||
}
|
||||
return builder.build();
|
||||
.putAllHeaders(uploadDescriptor.headers()))
|
||||
.build();
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -221,7 +218,7 @@ public class BackupsAnonymousGrpcService extends SimpleBackupsAnonymousGrpc.Back
|
||||
// uint32 in proto, make sure it fits in a signed int
|
||||
fromUnsignedExact(item.getObjectLength()),
|
||||
new MediaEncryptionParameters(item.getEncryptionKey().toByteArray(), item.getHmacKey().toByteArray()),
|
||||
item.getMediaId().toByteArray())).toList());
|
||||
item.getMediaId().toByteArray())).toList(), maxAttachmentSize);
|
||||
} catch (BackupFailedZkAuthenticationException e) {
|
||||
return JdkFlowAdapter.publisherToFlowPublisher(Mono.just(CopyMediaResponse
|
||||
.newBuilder()
|
||||
|
||||
@@ -19,6 +19,7 @@ import org.signal.chat.keys.DevicePreKeyBundle;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.KeyIdUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.KeysManager;
|
||||
|
||||
class KeysGrpcHelper {
|
||||
@@ -67,19 +68,20 @@ class KeysGrpcHelper {
|
||||
preKeysByDeviceId.forEach((deviceId, devicePreKeys) -> {
|
||||
final Device device = targetAccount.getDevice(deviceId).orElseThrow();
|
||||
|
||||
|
||||
final DevicePreKeyBundle.Builder builder = DevicePreKeyBundle.newBuilder()
|
||||
.setEcSignedPreKey(EcSignedPreKey.newBuilder()
|
||||
.setKeyId(devicePreKeys.ecSignedPreKey().keyId())
|
||||
.setKeyId(KeyIdUtil.toUnsignedInt(devicePreKeys.ecSignedPreKey().keyId()))
|
||||
.setPublicKey(ByteString.copyFrom(devicePreKeys.ecSignedPreKey().serializedPublicKey()))
|
||||
.setSignature(ByteString.copyFrom(devicePreKeys.ecSignedPreKey().signature())))
|
||||
.setKemOneTimePreKey(KemSignedPreKey.newBuilder()
|
||||
.setKeyId(devicePreKeys.kemSignedPreKey().keyId())
|
||||
.setKeyId(KeyIdUtil.toUnsignedInt(devicePreKeys.kemSignedPreKey().keyId()))
|
||||
.setPublicKey(ByteString.copyFrom(devicePreKeys.kemSignedPreKey().serializedPublicKey()))
|
||||
.setSignature(ByteString.copyFrom(devicePreKeys.kemSignedPreKey().signature())))
|
||||
.setRegistrationId(device.getRegistrationId(targetServiceIdentifier.identityType()));
|
||||
|
||||
devicePreKeys.ecPreKey().ifPresent(ecPreKey -> builder.setEcOneTimePreKey(EcPreKey.newBuilder()
|
||||
.setKeyId(ecPreKey.keyId())
|
||||
.setKeyId(KeyIdUtil.toUnsignedInt(ecPreKey.keyId()))
|
||||
.setPublicKey(ByteString.copyFrom(ecPreKey.serializedPublicKey()))));
|
||||
|
||||
preKeyBundlesBuilder.putDevicePreKeys(deviceId, builder.build());
|
||||
|
||||
@@ -7,6 +7,7 @@ package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import io.grpc.StatusRuntimeException;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.function.BiFunction;
|
||||
@@ -31,6 +32,7 @@ import org.signal.libsignal.protocol.kem.KEMPublicKey;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitKeys;
|
||||
import org.whispersystems.textsecuregcm.entities.ECPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
|
||||
@@ -96,18 +98,28 @@ public class KeysGrpcService extends SimpleKeysGrpc.KeysImplBase {
|
||||
final ServiceIdentifier targetIdentifier =
|
||||
ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getTargetIdentifier());
|
||||
|
||||
|
||||
final Optional<Account> maybeTargetAccount = accountsManager.getByServiceIdentifier(targetIdentifier);
|
||||
|
||||
final byte deviceId = request.hasDeviceId()
|
||||
? DeviceIdUtil.validate(request.getDeviceId())
|
||||
: KeysGrpcHelper.ALL_DEVICES;
|
||||
|
||||
final String rateLimitKey = authenticatedDevice.accountIdentifier() + "." +
|
||||
authenticatedDevice.deviceId() + "__" +
|
||||
targetIdentifier.uuid() + "." +
|
||||
deviceId;
|
||||
final Optional<Integer> targetRegistrationId = maybeTargetAccount
|
||||
.filter(_ -> request.hasDeviceId())
|
||||
.flatMap(targetAccount -> targetAccount.getDevice(deviceId))
|
||||
.map(device -> device.getRegistrationId(targetIdentifier.identityType()));
|
||||
|
||||
final String rateLimitKey = RateLimitKeys.preKeyLimiterKey(
|
||||
authenticatedDevice.accountIdentifier(),
|
||||
authenticatedDevice.deviceId(),
|
||||
targetIdentifier,
|
||||
Optional.ofNullable(request.hasDeviceId() ? deviceId : null),
|
||||
targetRegistrationId);
|
||||
|
||||
rateLimiters.getPreKeysLimiter().validate(rateLimitKey);
|
||||
|
||||
return accountsManager.getByServiceIdentifier(targetIdentifier)
|
||||
return maybeTargetAccount
|
||||
.flatMap(targetAccount -> KeysGrpcHelper.getPreKeys(targetAccount, targetIdentifier, deviceId, keysManager))
|
||||
.map(accountPreKeyBundles -> GetPreKeysResponse.newBuilder()
|
||||
.setPreKeys(accountPreKeyBundles)
|
||||
|
||||
+10
-8
@@ -295,14 +295,16 @@ public class MessagesAnonymousGrpcService extends SimpleMessagesAnonymousGrpc.Me
|
||||
MessageUtil.resolveRecipients(accountsManager, multiRecipientMessage);
|
||||
|
||||
try {
|
||||
messageSender.sendMultiRecipientMessage(multiRecipientMessage,
|
||||
resolvedRecipients,
|
||||
timestamp,
|
||||
story,
|
||||
ephemeral,
|
||||
urgent,
|
||||
RequestAttributesUtil.getUserAgent().orElse(null))
|
||||
.join();
|
||||
if (!resolvedRecipients.isEmpty()) {
|
||||
messageSender.sendMultiRecipientMessage(multiRecipientMessage,
|
||||
resolvedRecipients,
|
||||
timestamp,
|
||||
story,
|
||||
ephemeral,
|
||||
urgent,
|
||||
RequestAttributesUtil.getUserAgent().orElse(null))
|
||||
.join();
|
||||
}
|
||||
|
||||
final MultiRecipientSuccess.Builder responseBuilder = MultiRecipientSuccess.newBuilder();
|
||||
|
||||
|
||||
+23
-3
@@ -7,6 +7,7 @@ package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.protobuf.Descriptors;
|
||||
import com.google.protobuf.GeneratedMessage;
|
||||
import com.google.protobuf.InvalidProtocolBufferException;
|
||||
import com.google.protobuf.Message;
|
||||
import com.google.rpc.ErrorInfo;
|
||||
@@ -26,6 +27,7 @@ import io.micrometer.core.instrument.Timer;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import javax.annotation.Nullable;
|
||||
@@ -46,15 +48,19 @@ public class MetricServerInterceptor implements ServerInterceptor {
|
||||
private static final String TAG_REASON = "reason";
|
||||
|
||||
@VisibleForTesting
|
||||
static final String DEFAULT_SUCCESS_REASON = "success";
|
||||
static final String DEFAULT_SUCCESS_REASON = "SUCCESS";
|
||||
@VisibleForTesting
|
||||
static final String DEFAULT_ERROR_REASON = "n/a";
|
||||
static final String DEFAULT_ERROR_REASON = "N/A";
|
||||
|
||||
@VisibleForTesting
|
||||
static final String REQUEST_MESSAGE_COUNTER_NAME = MetricsUtil.name(MetricServerInterceptor.class, "requestMessage");
|
||||
@VisibleForTesting
|
||||
static final String REQUEST_BYTES_COUNTER_NAME = MetricsUtil.name(MetricServerInterceptor.class, "requestBytes");
|
||||
@VisibleForTesting
|
||||
static final String RESPONSE_COUNTER_NAME = MetricsUtil.name(MetricServerInterceptor.class, "responseMessage");
|
||||
@VisibleForTesting
|
||||
static final String RESPONSE_BYTES_COUNTER_NAME = MetricsUtil.name(MetricServerInterceptor.class, "responseBytes");
|
||||
@VisibleForTesting
|
||||
static final String RPC_COUNTER_NAME = MetricsUtil.name(MetricServerInterceptor.class, "rpc");
|
||||
@VisibleForTesting
|
||||
static final String DURATION_TIMER_NAME = MetricsUtil.name(MetricServerInterceptor.class, "processingDuration");
|
||||
@@ -99,12 +105,14 @@ public class MetricServerInterceptor implements ServerInterceptor {
|
||||
private class MetricServerCall<ReqT, RespT> extends ForwardingServerCall.SimpleForwardingServerCall<ReqT, RespT> {
|
||||
|
||||
private final Counter responseMessageCounter;
|
||||
private final Counter responseBytesCounter;
|
||||
private final Tags tags;
|
||||
private @Nullable String reason = null;
|
||||
|
||||
MetricServerCall(final ServerCall<ReqT, RespT> delegate, final Tags tags) {
|
||||
super(delegate);
|
||||
this.responseMessageCounter = meterRegistry.counter(RESPONSE_COUNTER_NAME, tags);
|
||||
this.responseBytesCounter = meterRegistry.counter(RESPONSE_BYTES_COUNTER_NAME, tags);
|
||||
this.tags = tags;
|
||||
}
|
||||
|
||||
@@ -117,7 +125,7 @@ public class MetricServerInterceptor implements ServerInterceptor {
|
||||
}
|
||||
Tags responseTags = tags.and(Tag.of(TAG_STATUS_CODE, status.getCode().name()));
|
||||
if (reason != null) {
|
||||
responseTags = responseTags.and(TAG_REASON, reason);
|
||||
responseTags = responseTags.and(TAG_REASON, reason.toUpperCase(Locale.ROOT));
|
||||
}
|
||||
meterRegistry.counter(RPC_COUNTER_NAME, responseTags).increment();
|
||||
super.close(status, responseHeaders);
|
||||
@@ -126,6 +134,11 @@ public class MetricServerInterceptor implements ServerInterceptor {
|
||||
@Override
|
||||
public void sendMessage(final RespT responseMessage) {
|
||||
this.responseMessageCounter.increment();
|
||||
|
||||
if (responseMessage instanceof GeneratedMessage generatedMessage) {
|
||||
this.responseBytesCounter.increment(generatedMessage.getSerializedSize());
|
||||
}
|
||||
|
||||
// Extract the annotated reason (if any) from the message
|
||||
final String messageReason = MetricServerCall.reason(responseMessage);
|
||||
|
||||
@@ -171,12 +184,14 @@ public class MetricServerInterceptor implements ServerInterceptor {
|
||||
private class MetricServerCallListener<ReqT> extends ForwardingServerCallListener.SimpleForwardingServerCallListener<ReqT> {
|
||||
|
||||
private final Counter requestCounter;
|
||||
private final Counter requestBytesCounter;
|
||||
private final Timer responseTimer;
|
||||
private final Timer.Sample sample;
|
||||
|
||||
MetricServerCallListener(final ServerCall.Listener<ReqT> delegate, final Tags tags) {
|
||||
super(delegate);
|
||||
this.requestCounter = meterRegistry.counter(REQUEST_MESSAGE_COUNTER_NAME, tags);
|
||||
this.requestBytesCounter = meterRegistry.counter(REQUEST_BYTES_COUNTER_NAME, tags);
|
||||
this.responseTimer = meterRegistry.timer(DURATION_TIMER_NAME, tags);
|
||||
this.sample = Timer.start(meterRegistry);
|
||||
}
|
||||
@@ -184,6 +199,11 @@ public class MetricServerInterceptor implements ServerInterceptor {
|
||||
@Override
|
||||
public void onMessage(final ReqT requestMessage) {
|
||||
this.requestCounter.increment();
|
||||
|
||||
if (requestMessage instanceof GeneratedMessage generatedMessage) {
|
||||
this.requestBytesCounter.increment(generatedMessage.getSerializedSize());
|
||||
}
|
||||
|
||||
super.onMessage(requestMessage);
|
||||
}
|
||||
|
||||
|
||||
+3
-1
@@ -17,6 +17,7 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.grpc.validators.Base64UrlFieldValidator;
|
||||
import org.whispersystems.textsecuregcm.grpc.validators.E164FieldValidator;
|
||||
import org.whispersystems.textsecuregcm.grpc.validators.EnumSpecifiedFieldValidator;
|
||||
import org.whispersystems.textsecuregcm.grpc.validators.ExactlySizeFieldValidator;
|
||||
@@ -37,7 +38,8 @@ public class ValidatingInterceptor implements ServerInterceptor {
|
||||
"org.signal.chat.require.e164", new E164FieldValidator(),
|
||||
"org.signal.chat.require.exactlySize", new ExactlySizeFieldValidator(),
|
||||
"org.signal.chat.require.range", new RangeFieldValidator(),
|
||||
"org.signal.chat.require.size", new SizeFieldValidator()
|
||||
"org.signal.chat.require.size", new SizeFieldValidator(),
|
||||
"org.signal.chat.require.base64url", new Base64UrlFieldValidator()
|
||||
);
|
||||
|
||||
@Override
|
||||
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.grpc.validators;
|
||||
|
||||
import com.google.protobuf.Descriptors;
|
||||
import org.whispersystems.textsecuregcm.util.ImpossiblePhoneNumberException;
|
||||
import org.whispersystems.textsecuregcm.util.NonNormalizedPhoneNumberException;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
import java.util.Base64;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
|
||||
/// Validate that a string field is a valid base64 url string (padded or unpadded)
|
||||
public class Base64UrlFieldValidator extends BaseFieldValidator<Boolean> {
|
||||
|
||||
public Base64UrlFieldValidator() {
|
||||
super("base64url", Set.of(Descriptors.FieldDescriptor.Type.STRING), MissingOptionalAction.SUCCEED, false);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Boolean resolveExtensionValue(final Object extensionValue) throws FieldValidationException {
|
||||
return requireFlagExtension(extensionValue);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void validateStringValue(
|
||||
final Boolean extensionValue,
|
||||
final String fieldValue) throws FieldValidationException {
|
||||
try {
|
||||
Base64.getUrlDecoder().decode(fieldValue);
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw new FieldValidationException("value is not valid base64 url");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,6 @@ package org.whispersystems.textsecuregcm.limits;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
public interface RateLimiter {
|
||||
@@ -78,4 +77,27 @@ public interface RateLimiter {
|
||||
default CompletionStage<Void> clearAsync(final UUID accountUuid) {
|
||||
return clearAsync(accountUuid.toString());
|
||||
}
|
||||
|
||||
/// Restore `permitsToRestore` permits to the pool. If the RateLimiter has a maximum bucket size, it is respected even
|
||||
/// if `permitsToRestore` would exceed the maximum bucket size.
|
||||
///
|
||||
/// @param key The key to restore permits for.
|
||||
/// @param permitsToRestore The number of permits to restore
|
||||
/// @implNote The default implementation of this method assumes permits can be restored by calling `validate` with a
|
||||
/// negative permit count. If the `validate` implementation does not support this, the implementor must provide a
|
||||
/// custom implementation of [this#restorePermits].
|
||||
default void restorePermits(final String key, int permitsToRestore) {
|
||||
if (permitsToRestore < 0) {
|
||||
throw new IllegalArgumentException("permits to restore must be non-negative");
|
||||
}
|
||||
try {
|
||||
validate(key, -1 * permitsToRestore);
|
||||
} catch (RateLimitExceededException e) {
|
||||
throw new IllegalStateException("Out of permits when trying to restore permits", e);
|
||||
}
|
||||
}
|
||||
|
||||
default void restorePermits(final UUID accountUuid, int permitsToRestore) {
|
||||
restorePermits(accountUuid.toString(), permitsToRestore);
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import com.google.common.annotations.VisibleForTesting;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import io.dropwizard.util.DataSize;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
@@ -19,6 +20,7 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
|
||||
BACKUP_AUTH_CHECK("backupAuthCheck", new RateLimiterConfig(100, Duration.ofMinutes(15), true)),
|
||||
PIN("pin", new RateLimiterConfig(10, Duration.ofDays(1), false)),
|
||||
ATTACHMENT("attachmentCreate", new RateLimiterConfig(50, Duration.ofMillis(1200), true)),
|
||||
ATTACHMENT_BYTES("attachmentCreateBytes", new RateLimiterConfig(DataSize.gigabytes(1).toBytes(), Duration.ofNanos(1000), true)),
|
||||
BACKUP_ATTACHMENT("backupAttachmentCreate", new RateLimiterConfig(10_000, Duration.ofSeconds(1), true)),
|
||||
PRE_KEYS("prekeys", new RateLimiterConfig(6, Duration.ofMinutes(10), false)),
|
||||
MESSAGES("messages", new RateLimiterConfig(60, Duration.ofSeconds(1), true)),
|
||||
@@ -115,6 +117,10 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
|
||||
return forDescriptor(For.ATTACHMENT);
|
||||
}
|
||||
|
||||
public RateLimiter getAttachmentBytesLimiter() {
|
||||
return forDescriptor(For.ATTACHMENT_BYTES);
|
||||
}
|
||||
|
||||
public RateLimiter getPinLimiter() {
|
||||
return forDescriptor(For.PIN);
|
||||
}
|
||||
|
||||
+14
-2
@@ -18,9 +18,11 @@ import jakarta.ws.rs.container.ContainerResponseFilter;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import javax.annotation.Nullable;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.eclipse.jetty.server.Connector;
|
||||
import org.eclipse.jetty.server.HttpChannel;
|
||||
import org.eclipse.jetty.server.Request;
|
||||
@@ -49,6 +51,9 @@ import org.whispersystems.textsecuregcm.util.ua.UserAgentUtil;
|
||||
public class MetricsHttpChannelListener implements HttpChannel.Listener, Container.Listener, LifeCycle.Listener,
|
||||
ContainerResponseFilter {
|
||||
|
||||
private static final Set<String> EXPECTED_HTTP_METHODS =
|
||||
Set.of("GET", "HEAD", "POST", "PUT", "DELETE", "CONNECT", "OPTIONS", "TRACE", "PATCH");
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(MetricsHttpChannelListener.class);
|
||||
|
||||
private record RequestInfo(String path, String method, int statusCode, @Nullable String userAgent) {
|
||||
@@ -201,14 +206,21 @@ public class MetricsHttpChannelListener implements HttpChannel.Listener, Contain
|
||||
.filter(servletPaths::contains)
|
||||
.orElse("unknown")
|
||||
);
|
||||
final String method = Optional.ofNullable(request.getMethod()).orElse("unknown");
|
||||
|
||||
// Response cannot be null, but its status might not always reflect an actual response status, since it gets
|
||||
// initialized to 200
|
||||
final int status = request.getResponse().getStatus();
|
||||
|
||||
@Nullable final String userAgent = request.getHeader(HttpHeaders.USER_AGENT);
|
||||
|
||||
return new RequestInfo(path, method, status, userAgent);
|
||||
return new RequestInfo(path, normalizeMethod(request.getMethod()), status, userAgent);
|
||||
}
|
||||
|
||||
static String normalizeMethod(@Nullable final String method) {
|
||||
if (StringUtils.isBlank(method)) {
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
return EXPECTED_HTTP_METHODS.contains(method.toUpperCase(Locale.ROOT)) ? method : "unknown";
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -107,7 +107,7 @@ public class MetricsRequestEventListener implements RequestEventListener {
|
||||
|
||||
final List<Tag> tags = new ArrayList<>();
|
||||
tags.add(Tag.of(PATH_TAG, UriInfoUtil.getPathTemplate(event.getUriInfo())));
|
||||
tags.add(Tag.of(METHOD_TAG, event.getContainerRequest().getMethod()));
|
||||
tags.add(Tag.of(METHOD_TAG, MetricsHttpChannelListener.normalizeMethod(event.getContainerRequest().getMethod())));
|
||||
tags.add(Tag.of(STATUS_CODE_TAG, String.valueOf(Optional
|
||||
.ofNullable(event.getContainerResponse())
|
||||
.map(ContainerResponse::getStatus)
|
||||
|
||||
+13
@@ -8,6 +8,7 @@ import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import java.util.Optional;
|
||||
import org.whispersystems.textsecuregcm.entities.UpdateVerificationSessionRequest;
|
||||
import org.whispersystems.textsecuregcm.registration.VerificationSession;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
|
||||
public interface RegistrationFraudChecker {
|
||||
|
||||
@@ -47,6 +48,14 @@ public interface RegistrationFraudChecker {
|
||||
final VerificationSession verificationSession,
|
||||
final String e164);
|
||||
|
||||
/**
|
||||
* Handles a completed verification session resulting in a registration.
|
||||
*
|
||||
* @param verificationSessionId The ID of the verification session that resulted in a completed registration
|
||||
* @param createdAccount The account created at the end of the verification session
|
||||
*/
|
||||
void handleVerificationCompleted(final String verificationSessionId, final Account createdAccount);
|
||||
|
||||
static RegistrationFraudChecker noop() {
|
||||
return new RegistrationFraudChecker() {
|
||||
|
||||
@@ -64,6 +73,10 @@ public interface RegistrationFraudChecker {
|
||||
|
||||
return VerificationCheck.DEFAULT;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleVerificationCompleted(final String verificationSessionId, final Account createdAccount) {
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import static java.util.Objects.requireNonNull;
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
import static org.whispersystems.textsecuregcm.util.Util.getAlternateForms;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectWriter;
|
||||
@@ -371,7 +372,28 @@ public class Accounts {
|
||||
.build())
|
||||
.build());
|
||||
}
|
||||
writeItems.add(UpdateAccountSpec.forAccount(accountsTableName, accountToCreate).transactItem());
|
||||
|
||||
// Phone number canonicalization means that a user can use a different phone number in the same equivalence class
|
||||
// to reclaim the account.
|
||||
if (!existingAccount.getNumber().equals(accountToCreate.getNumber())) {
|
||||
if (getAlternateForms(existingAccount.getNumber()).contains(accountToCreate.getNumber())) {
|
||||
final AttributeValue uuidAttr = AttributeValues.fromUUID(existingAccount.getUuid());
|
||||
final AttributeValue numberAttr = AttributeValues.fromString(accountToCreate.getNumber());
|
||||
final TransactWriteItem phoneNumberConstraintPut = buildConstraintTablePutIfAbsent(
|
||||
phoneNumberConstraintTableName, uuidAttr, ATTR_ACCOUNT_E164, numberAttr);
|
||||
|
||||
writeItems.add(buildDelete(phoneNumberConstraintTableName, ATTR_ACCOUNT_E164, existingAccount.getNumber()));
|
||||
writeItems.add(phoneNumberConstraintPut);
|
||||
} else {
|
||||
log.error("Reclaiming account with a non-equivalent phone number. Old account {}:{}:{}, new account {}:{}:{}",
|
||||
existingAccount.getUuid(), existingAccount.getNumber(), existingAccount.getPhoneNumberIdentifier(),
|
||||
accountToCreate.getUuid(), accountToCreate.getNumber(), accountToCreate.getPhoneNumberIdentifier());
|
||||
throw new IllegalArgumentException("reclaimed accounts must have equivalent phone numbers");
|
||||
}
|
||||
}
|
||||
|
||||
final int updateAccountItemIndex = writeItems.size();
|
||||
writeItems.add(UpdateAccountSpec.forReclaimedAccount(accountsTableName, accountToCreate, existingAccount.getNumber()).transactItem());
|
||||
writeItems.addAll(additionalWriteItems);
|
||||
|
||||
return dynamoDbAsyncClient.transactWriteItems(TransactWriteItemsRequest.builder().transactItems(writeItems).build())
|
||||
@@ -382,6 +404,16 @@ public class Accounts {
|
||||
.exceptionally(throwable -> {
|
||||
final Throwable unwrapped = ExceptionUtils.unwrap(throwable);
|
||||
if (unwrapped instanceof TransactionCanceledException te) {
|
||||
if (Accounts.conditionalCheckFailed(te.cancellationReasons().get(updateAccountItemIndex))) {
|
||||
final Map<String, AttributeValue> item = te.cancellationReasons().get(updateAccountItemIndex).item();
|
||||
final String existingNumber = AttributeValues.getString(item, Accounts.ATTR_ACCOUNT_E164, null);
|
||||
if (!existingAccount.getNumber().equals(existingNumber)) {
|
||||
log.error("Failed to update account due to unexpected existing phone number. Account {}. Expected {}, got {}",
|
||||
existingAccount.getUuid(), existingAccount.getNumber(), existingNumber);
|
||||
throw new UnexpectedExistingPhoneNumberException();
|
||||
}
|
||||
}
|
||||
|
||||
if (te.cancellationReasons().stream().anyMatch(Accounts::conditionalCheckFailed)) {
|
||||
throw new ContestedOptimisticLockException();
|
||||
}
|
||||
@@ -889,6 +921,37 @@ public class Accounts {
|
||||
}
|
||||
}
|
||||
|
||||
record UpdateExpression (List<String> setClauses, List<String> addClauses, List<String> removeClauses) {
|
||||
public String toExpressionString() {
|
||||
final StringBuilder updateExpressionBuilder = new StringBuilder();
|
||||
|
||||
if (!setClauses.isEmpty()) {
|
||||
updateExpressionBuilder.append("SET ");
|
||||
updateExpressionBuilder.append(String.join(", ", setClauses));
|
||||
}
|
||||
|
||||
if (!removeClauses.isEmpty()) {
|
||||
if (!updateExpressionBuilder.isEmpty()) {
|
||||
updateExpressionBuilder.append(" ");
|
||||
}
|
||||
|
||||
updateExpressionBuilder.append("REMOVE ");
|
||||
updateExpressionBuilder.append(String.join(", ", removeClauses));
|
||||
}
|
||||
|
||||
if (!addClauses.isEmpty()) {
|
||||
if (!updateExpressionBuilder.isEmpty()) {
|
||||
updateExpressionBuilder.append(" ");
|
||||
}
|
||||
|
||||
updateExpressionBuilder.append("ADD ");
|
||||
updateExpressionBuilder.append(String.join(", ", addClauses));
|
||||
}
|
||||
|
||||
return updateExpressionBuilder.toString();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A ddb update that can be used as part of a transaction or single-item update statement.
|
||||
*/
|
||||
@@ -897,13 +960,13 @@ public class Accounts {
|
||||
Map<String, AttributeValue> key,
|
||||
Map<String, String> attrNames,
|
||||
Map<String, AttributeValue> attrValues,
|
||||
String updateExpression,
|
||||
UpdateExpression updateExpression,
|
||||
String conditionExpression) {
|
||||
UpdateItemRequest updateItemRequest() {
|
||||
return UpdateItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.key(key)
|
||||
.updateExpression(updateExpression)
|
||||
.updateExpression(updateExpression.toExpressionString())
|
||||
.conditionExpression(conditionExpression)
|
||||
.expressionAttributeNames(attrNames)
|
||||
.expressionAttributeValues(attrValues)
|
||||
@@ -914,17 +977,46 @@ public class Accounts {
|
||||
return TransactWriteItem.builder().update(Update.builder()
|
||||
.tableName(tableName)
|
||||
.key(key)
|
||||
.updateExpression(updateExpression)
|
||||
.updateExpression(updateExpression.toExpressionString())
|
||||
.conditionExpression(conditionExpression)
|
||||
.returnValuesOnConditionCheckFailure(ReturnValuesOnConditionCheckFailure.ALL_OLD)
|
||||
.expressionAttributeNames(attrNames)
|
||||
.expressionAttributeValues(attrValues)
|
||||
.build()).build();
|
||||
}
|
||||
|
||||
static UpdateAccountSpec forReclaimedAccount(
|
||||
final String accountTableName,
|
||||
final Account account,
|
||||
final String expectedExistingE164) {
|
||||
final UpdateAccountSpec base = forAccount(accountTableName, account);
|
||||
|
||||
final Map<String, AttributeValue> attrValues = new HashMap<>(base.attrValues());
|
||||
attrValues.put(":number", AttributeValues.fromString(account.getNumber()));
|
||||
|
||||
final UpdateExpression updateExpression = base.updateExpression();
|
||||
final List<String> setClauses = new ArrayList<>(updateExpression.setClauses());
|
||||
setClauses.add("#number = :number");
|
||||
|
||||
final MembershipExpression membershipExpression = MembershipExpression.build(getAlternateForms(expectedExistingE164));
|
||||
attrValues.putAll(membershipExpression.values());
|
||||
|
||||
// Defensive check: we should only update the e164 to another e164 in the same equivalence class
|
||||
final String conditionExpression = base.conditionExpression() + " AND #number IN %s".formatted(membershipExpression.expression());
|
||||
|
||||
return new UpdateAccountSpec(
|
||||
base.tableName(),
|
||||
base.key(),
|
||||
base.attrNames(),
|
||||
attrValues,
|
||||
new UpdateExpression(setClauses, updateExpression.addClauses(), updateExpression.removeClauses()),
|
||||
conditionExpression
|
||||
);
|
||||
}
|
||||
|
||||
static UpdateAccountSpec forAccount(
|
||||
final String accountTableName,
|
||||
final Account account) {
|
||||
// username, e164, and pni cannot be modified through this method
|
||||
final Map<String, String> attrNames = new HashMap<>(Map.of(
|
||||
"#number", ATTR_ACCOUNT_E164,
|
||||
"#data", ATTR_ACCOUNT_DATA,
|
||||
@@ -937,19 +1029,20 @@ public class Accounts {
|
||||
":version", AttributeValues.fromInt(account.getVersion()),
|
||||
":version_increment", AttributeValues.fromInt(1)));
|
||||
|
||||
final StringBuilder updateExpressionBuilder = new StringBuilder("SET #data = :data, #cds = :cds");
|
||||
final List<String> setClauses = new ArrayList<>(List.of("#data = :data", "#cds = :cds"));
|
||||
|
||||
if (account.getUnidentifiedAccessKey().isPresent()) {
|
||||
// if it's present in the account, also set the uak
|
||||
attrNames.put("#uak", ATTR_UAK);
|
||||
attrValues.put(":uak", AttributeValues.fromByteArray(account.getUnidentifiedAccessKey().get()));
|
||||
updateExpressionBuilder.append(", #uak = :uak");
|
||||
setClauses.add("#uak = :uak");
|
||||
}
|
||||
|
||||
if (account.getUsernameHash().isPresent()) {
|
||||
// if it's present in the account, also set the username hash
|
||||
attrNames.put("#usernameHash", ATTR_USERNAME_HASH);
|
||||
attrValues.put(":usernameHash", AttributeValues.fromByteArray(account.getUsernameHash().get()));
|
||||
updateExpressionBuilder.append(", #usernameHash = :usernameHash");
|
||||
setClauses.add("#usernameHash = :usernameHash");
|
||||
}
|
||||
|
||||
// If the account has a username/handle pair, we should add it to the top level attributes.
|
||||
@@ -959,7 +1052,7 @@ public class Accounts {
|
||||
if (account.getEncryptedUsername().isPresent() && account.getUsernameLinkHandle() != null) {
|
||||
attrNames.put("#ul", ATTR_USERNAME_LINK_UUID);
|
||||
attrValues.put(":ul", AttributeValues.fromUUID(account.getUsernameLinkHandle()));
|
||||
updateExpressionBuilder.append(", #ul = :ul");
|
||||
setClauses.add("#ul = :ul");
|
||||
}
|
||||
|
||||
// Some operations may remove the usernameLink or the usernameHash (re-registration, clear username link, and
|
||||
@@ -974,17 +1067,20 @@ public class Accounts {
|
||||
attrNames.put("#username_hash", ATTR_USERNAME_HASH);
|
||||
removes.add("#username_hash");
|
||||
}
|
||||
|
||||
final List<String> removeClauses = new ArrayList<>();
|
||||
if (!removes.isEmpty()) {
|
||||
updateExpressionBuilder.append(" REMOVE %s".formatted(String.join(",", removes)));
|
||||
removeClauses.add(String.join(",", removes));
|
||||
}
|
||||
updateExpressionBuilder.append(" ADD #version :version_increment");
|
||||
|
||||
final List<String> addClauses = List.of("#version :version_increment");
|
||||
|
||||
return new UpdateAccountSpec(
|
||||
accountTableName,
|
||||
Map.of(KEY_ACCOUNT_UUID, AttributeValues.fromUUID(account.getUuid())),
|
||||
attrNames,
|
||||
attrValues,
|
||||
updateExpressionBuilder.toString(),
|
||||
new UpdateExpression(setClauses, addClauses, removeClauses),
|
||||
"attribute_exists(#number) AND #version = :version");
|
||||
}
|
||||
}
|
||||
@@ -1584,4 +1680,26 @@ public class Accounts {
|
||||
: phoneNumber.substring(phoneNumber.length() - 2));
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
record MembershipExpression(String expression, Map<String, AttributeValue> values) {
|
||||
public static MembershipExpression build(final Collection<String> values) {
|
||||
if (values.isEmpty()) {
|
||||
throw new IllegalArgumentException("must have at least one value");
|
||||
}
|
||||
|
||||
final Map<String, AttributeValue> expressionValues = new HashMap<>();
|
||||
final List<String> placeholders = new ArrayList<>();
|
||||
final String prefix = "val";
|
||||
int i = 0;
|
||||
for (final String value : values) {
|
||||
String key = ":" + prefix + i;
|
||||
placeholders.add(key);
|
||||
expressionValues.put(key, AttributeValues.fromString(value));
|
||||
i++;
|
||||
}
|
||||
|
||||
final String expression = "(" + String.join(", ", placeholders) + ")";
|
||||
return new MembershipExpression(expression, expressionValues);
|
||||
}
|
||||
}
|
||||
}
|
||||
+19
-19
@@ -6,6 +6,7 @@
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.EnumSet;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
@@ -36,42 +37,41 @@ public enum DeviceCapability {
|
||||
ALWAYS_CAPABLE,
|
||||
}
|
||||
|
||||
public static final Set<DeviceCapability> CAPABILITIES_REQUIRED_FOR_REGISTRATION =
|
||||
Arrays.stream(DeviceCapability.values())
|
||||
.filter(DeviceCapability::requireForRegistration)
|
||||
.collect(Collectors.toSet());
|
||||
public static final Set<DeviceCapability> CAPABILITIES_REQUIRED_FOR_NEW_DEVICES =
|
||||
EnumSet.copyOf(Arrays.stream(DeviceCapability.values())
|
||||
.filter(DeviceCapability::requireForNewDevices)
|
||||
.collect(Collectors.toSet()));
|
||||
|
||||
private final String name;
|
||||
private final AccountCapabilityMode accountCapabilityMode;
|
||||
private final boolean preventDowngrade;
|
||||
private final boolean includeInProfile;
|
||||
private final boolean requireForRegistration;
|
||||
private final boolean requireForNewDevices;
|
||||
|
||||
/**
|
||||
* Create a DeviceCapability
|
||||
*
|
||||
* @param name The name of the device capability that clients will see
|
||||
* @param accountCapabilityMode How to combine the constituent device's capabilities in the account to an overall
|
||||
* account capability
|
||||
* @param preventDowngrade If true, don't let linked devices join that don't have a device capability if the
|
||||
* overall account has the capability. Most of the time this should only be used in
|
||||
* conjunction with AccountCapabilityMode.ALL_DEVICES.
|
||||
* @param includeInProfile Whether to return this capability on the account's profile. If false, the capability
|
||||
* is only visible to the server.
|
||||
* @param requireForRegistration If true, prevent account creation if the account's initial device does not have this
|
||||
* capability
|
||||
* @param name The name of the device capability that clients will see
|
||||
* @param accountCapabilityMode How to combine the constituent device's capabilities in the account to an overall
|
||||
* account capability
|
||||
* @param preventDowngrade If true, don't let linked devices join that don't have a device capability if the
|
||||
* overall account has the capability. Most of the time this should only be used in
|
||||
* conjunction with AccountCapabilityMode.ALL_DEVICES.
|
||||
* @param includeInProfile Whether to return this capability on the account's profile. If false, the capability
|
||||
* is only visible to the server.
|
||||
* @param requireForNewDevices If true, prevent device creation if the new device does not have this capability
|
||||
*/
|
||||
DeviceCapability(final String name,
|
||||
final AccountCapabilityMode accountCapabilityMode,
|
||||
final boolean preventDowngrade,
|
||||
final boolean includeInProfile,
|
||||
final boolean requireForRegistration) {
|
||||
final boolean requireForNewDevices) {
|
||||
|
||||
this.name = name;
|
||||
this.accountCapabilityMode = accountCapabilityMode;
|
||||
this.preventDowngrade = preventDowngrade;
|
||||
this.includeInProfile = includeInProfile;
|
||||
this.requireForRegistration = requireForRegistration;
|
||||
this.requireForNewDevices = requireForNewDevices;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
@@ -90,8 +90,8 @@ public enum DeviceCapability {
|
||||
return includeInProfile;
|
||||
}
|
||||
|
||||
public boolean requireForRegistration() {
|
||||
return requireForRegistration;
|
||||
public boolean requireForNewDevices() {
|
||||
return requireForNewDevices;
|
||||
}
|
||||
|
||||
public static Optional<DeviceCapability> forName(final String name) {
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
public class KeyIdUtil {
|
||||
public static final long MAX_KEY_ID = (1L << 32) - 1;
|
||||
public static final long MIN_KEY_ID = 0;
|
||||
private KeyIdUtil(){}
|
||||
|
||||
public static boolean keyIdValid(final long keyId) {
|
||||
return keyId <= MAX_KEY_ID && keyId >= MIN_KEY_ID;
|
||||
}
|
||||
|
||||
/// Convert a long keyId (a 32-bit unsigned int) into an int representation.
|
||||
///
|
||||
/// The inverse of [Integer#toUnsignedLong].
|
||||
///
|
||||
/// @param keyId A key ID which must be in the range [0, 2^32)
|
||||
/// @throws IllegalArgumentException If `keyId` is not within the range
|
||||
/// @return A 32-bit unsigned integer where the top bit is stored in the sign bit
|
||||
public static int toUnsignedInt(final long keyId) {
|
||||
if (!keyIdValid(keyId)) {
|
||||
throw new IllegalArgumentException("Invalid keyId " + keyId);
|
||||
}
|
||||
return (int) keyId;
|
||||
}
|
||||
}
|
||||
+273
-183
@@ -9,19 +9,22 @@ import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.dropwizard.lifecycle.Managed;
|
||||
import io.lettuce.core.cluster.models.partitions.RedisClusterNode;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.DistributionSummary;
|
||||
import io.micrometer.core.instrument.LongTaskTimer;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import javax.annotation.Nullable;
|
||||
import org.apache.commons.lang3.tuple.Pair;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
@@ -32,7 +35,10 @@ import org.whispersystems.textsecuregcm.metrics.DevicePlatformUtil;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
import reactor.util.function.Tuples;
|
||||
import reactor.util.retry.Retry;
|
||||
import reactor.util.retry.RetryBackoffSpec;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ItemCollectionSizeLimitExceededException;
|
||||
|
||||
public class MessagePersister implements Managed {
|
||||
@@ -41,153 +47,228 @@ public class MessagePersister implements Managed {
|
||||
private final MessagesManager messagesManager;
|
||||
private final AccountsManager accountsManager;
|
||||
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
|
||||
private final Scheduler persistQueueScheduler;
|
||||
private final Clock clock;
|
||||
|
||||
private final Duration persistDelay;
|
||||
private final int maxConcurrency;
|
||||
private final int scanCount;
|
||||
|
||||
private final RetryBackoffSpec retryBackoffSpec;
|
||||
|
||||
private final String persisterId = UUID.randomUUID().toString();
|
||||
|
||||
private final Thread[] workerThreads;
|
||||
private volatile boolean running;
|
||||
|
||||
@Nullable
|
||||
private Thread workerThread;
|
||||
|
||||
private static final String INSPECTED_QUEUE_COUNTER_NAME = name(MessagePersister.class, "inspectedQueue");
|
||||
|
||||
private static final String OVERSIZED_QUEUE_COUNTER_NAME = name(MessagePersister.class, "persistQueueOversized");
|
||||
private static final String PERSISTED_MESSAGE_COUNTER_NAME = name(MessagePersister.class, "persistMessage");
|
||||
private static final String PERSISTED_BYTES_COUNTER_NAME = name(MessagePersister.class, "persistBytes");
|
||||
|
||||
private static final Timer GET_QUEUES_TIMER = Metrics.timer(name(MessagePersister.class, "getQueues"));
|
||||
private static final Timer PERSIST_QUEUE_TIMER = Metrics.timer(name(MessagePersister.class, "persistQueue"));
|
||||
private static final Counter PERSIST_QUEUE_EXCEPTION_METER =
|
||||
Metrics.counter(name(MessagePersister.class, "persistQueueException"));
|
||||
private static final Counter TRIMMED_MESSAGE_COUNTER = Metrics.counter(name(MessagePersister.class, "trimmedMessage"));
|
||||
private static final Counter TRIMMED_MESSAGE_BYTES_COUNTER = Metrics.counter(name(MessagePersister.class, "trimmedMessageBytes"));
|
||||
|
||||
private static final Counter PERSIST_NODE_COUNTER = Metrics.counter(name(MessagePersister.class, "persistNodeCount"));
|
||||
private static final LongTaskTimer PERSIST_NODE_TIMER = Metrics.more().longTaskTimer(name(MessagePersister.class, "persistNode"));
|
||||
|
||||
private static final String QUEUE_SIZE_DISTRIBUTION_SUMMARY_NAME = name(MessagePersister.class, "queueSize");
|
||||
|
||||
static final int QUEUE_BATCH_LIMIT = 100;
|
||||
static final int MESSAGE_BATCH_LIMIT = 100;
|
||||
|
||||
private static final DistributionSummary QUEUE_COUNT_DISTRIBUTION_SUMMARY = DistributionSummary.builder(
|
||||
name(MessagePersister.class, "queueCount"))
|
||||
.register(Metrics.globalRegistry);
|
||||
private static final DistributionSummary QUEUE_COUNT_DISTRIBUTION_SUMMARY =
|
||||
DistributionSummary.builder(name(MessagePersister.class, "queueCount"))
|
||||
.register(Metrics.globalRegistry);
|
||||
|
||||
private static final long EXCEPTION_PAUSE_MILLIS = Duration.ofSeconds(3).toMillis();
|
||||
|
||||
private static final int CONSECUTIVE_EMPTY_CACHE_REMOVAL_LIMIT = 3;
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(MessagePersister.class);
|
||||
|
||||
public MessagePersister(final MessagesCache messagesCache,
|
||||
final MessagesManager messagesManager,
|
||||
final AccountsManager accountsManager,
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
|
||||
final Scheduler persistQueueScheduler,
|
||||
final Clock clock,
|
||||
final Duration persistDelay,
|
||||
final int dedicatedProcessWorkerThreadCount) {
|
||||
final int maxConcurrency,
|
||||
final int scanCount) {
|
||||
|
||||
this(messagesCache,
|
||||
messagesManager,
|
||||
accountsManager,
|
||||
dynamicConfigurationManager,
|
||||
persistQueueScheduler,
|
||||
clock,
|
||||
persistDelay,
|
||||
maxConcurrency,
|
||||
scanCount,
|
||||
Retry.backoff(3, Duration.ofSeconds(1)));
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
MessagePersister(final MessagesCache messagesCache,
|
||||
final MessagesManager messagesManager,
|
||||
final AccountsManager accountsManager,
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
|
||||
final Scheduler persistQueueScheduler,
|
||||
final Clock clock,
|
||||
final Duration persistDelay,
|
||||
final int maxConcurrency,
|
||||
final int scanCount,
|
||||
final RetryBackoffSpec retryBackoffSpec) {
|
||||
|
||||
this.messagesCache = messagesCache;
|
||||
this.messagesManager = messagesManager;
|
||||
this.accountsManager = accountsManager;
|
||||
this.dynamicConfigurationManager = dynamicConfigurationManager;
|
||||
this.clock = clock;
|
||||
this.persistDelay = persistDelay;
|
||||
this.workerThreads = new Thread[dedicatedProcessWorkerThreadCount];
|
||||
|
||||
for (int i = 0; i < workerThreads.length; i++) {
|
||||
workerThreads[i] = new Thread(() -> {
|
||||
while (running) {
|
||||
if (dynamicConfigurationManager.getConfiguration().getMessagePersisterConfiguration()
|
||||
.isPersistenceEnabled()) {
|
||||
try {
|
||||
final int queuesPersisted = persistNextQueues(Instant.now());
|
||||
QUEUE_COUNT_DISTRIBUTION_SUMMARY.record(queuesPersisted);
|
||||
|
||||
if (queuesPersisted == 0) {
|
||||
Util.sleep(100);
|
||||
}
|
||||
} catch (final Throwable t) {
|
||||
logger.warn("Failed to persist queues", t);
|
||||
Util.sleep(EXCEPTION_PAUSE_MILLIS);
|
||||
}
|
||||
} else {
|
||||
Util.sleep(1000);
|
||||
}
|
||||
}
|
||||
}, "MessagePersisterWorker-" + i);
|
||||
}
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
Duration getPersistDelay() {
|
||||
return persistDelay;
|
||||
this.maxConcurrency = maxConcurrency;
|
||||
this.scanCount = scanCount;
|
||||
this.retryBackoffSpec = retryBackoffSpec;
|
||||
this.persistQueueScheduler = persistQueueScheduler;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void start() {
|
||||
public synchronized void start() {
|
||||
running = true;
|
||||
|
||||
for (final Thread workerThread : workerThreads) {
|
||||
workerThread.start();
|
||||
}
|
||||
workerThread = new Thread(() -> {
|
||||
while (running) {
|
||||
if (dynamicConfigurationManager.getConfiguration().getMessagePersisterConfiguration().isPersistenceEnabled()) {
|
||||
try {
|
||||
final int queuesPersisted = persistNextNode();
|
||||
QUEUE_COUNT_DISTRIBUTION_SUMMARY.record(queuesPersisted);
|
||||
|
||||
if (queuesPersisted == 0) {
|
||||
Util.sleep(100);
|
||||
}
|
||||
} catch (final Throwable t) {
|
||||
logger.warn("Failed to persist queues", t);
|
||||
Util.sleep(EXCEPTION_PAUSE_MILLIS);
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
// Persisters work through nodes quickly, and running in a hot loop taxes Redis nodes unnecessarily
|
||||
Thread.sleep(dynamicConfigurationManager.getConfiguration().getMessagePersisterConfiguration().getSleepBetweenNodes());
|
||||
} catch (final InterruptedException _) {
|
||||
}
|
||||
}
|
||||
}, "MessagePersister");
|
||||
|
||||
workerThread.start();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stop() {
|
||||
public synchronized void stop() {
|
||||
running = false;
|
||||
|
||||
for (final Thread workerThread : workerThreads) {
|
||||
if (workerThread != null) {
|
||||
try {
|
||||
workerThread.join();
|
||||
} catch (final InterruptedException e) {
|
||||
logger.warn("Interrupted while waiting for worker thread to complete current operation");
|
||||
}
|
||||
|
||||
workerThread = null;
|
||||
}
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
int persistNextQueues(final Instant currentTime) {
|
||||
final int slot = messagesCache.getNextSlotToPersist();
|
||||
final String shard = messagesCache.shardForSlot(slot);
|
||||
int persistNextNode() {
|
||||
final RedisClusterNode node;
|
||||
{
|
||||
final Duration nodeClaimTtl =
|
||||
dynamicConfigurationManager.getConfiguration().getMessagePersisterConfiguration().getNodeClaimTtl();
|
||||
|
||||
List<String> queuesToPersist;
|
||||
int queuesPersisted = 0;
|
||||
final Optional<RedisClusterNode> maybeNode = messagesCache.claimNextNodeToPersist(persisterId, nodeClaimTtl);
|
||||
|
||||
do {
|
||||
queuesToPersist = GET_QUEUES_TIMER.record(
|
||||
() -> messagesCache.getQueuesToPersist(slot, currentTime.minus(persistDelay), QUEUE_BATCH_LIMIT));
|
||||
|
||||
for (final String queue : queuesToPersist) {
|
||||
final UUID accountUuid = MessagesCache.getAccountUuidFromQueueName(queue);
|
||||
final byte deviceId = MessagesCache.getDeviceIdFromQueueName(queue);
|
||||
|
||||
final Optional<Account> maybeAccount = accountsManager.getByAccountIdentifier(accountUuid);
|
||||
if (maybeAccount.isEmpty()) {
|
||||
logger.error("No account record found for account {}", accountUuid);
|
||||
continue;
|
||||
}
|
||||
final Optional<Device> maybeDevice = maybeAccount.flatMap(account -> account.getDevice(deviceId));
|
||||
if (maybeDevice.isEmpty()) {
|
||||
logger.error("Account {} does not have a device with id {}", accountUuid, deviceId);
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
persistQueue(maybeAccount.get(), maybeDevice.get(), shard);
|
||||
} catch (final Exception e) {
|
||||
PERSIST_QUEUE_EXCEPTION_METER.increment();
|
||||
logger.warn("Failed to persist queue {}::{} (slot {}, shard {}); will schedule for retry",
|
||||
accountUuid, deviceId, slot, shard, e);
|
||||
|
||||
messagesCache.addQueueToPersist(accountUuid, deviceId);
|
||||
|
||||
if (!(e instanceof MessagePersistenceException)) {
|
||||
// Pause after unexpected exceptions
|
||||
Util.sleep(EXCEPTION_PAUSE_MILLIS);
|
||||
}
|
||||
}
|
||||
if (maybeNode.isEmpty()) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
queuesPersisted += queuesToPersist.size();
|
||||
} while (queuesToPersist.size() >= QUEUE_BATCH_LIMIT);
|
||||
node = maybeNode.get();
|
||||
}
|
||||
|
||||
return queuesPersisted;
|
||||
try {
|
||||
return persistNode(node);
|
||||
} finally {
|
||||
messagesCache.releaseNodeClaim(node, persisterId);
|
||||
}
|
||||
}
|
||||
|
||||
int persistNode(final RedisClusterNode node) {
|
||||
final LongTaskTimer.Sample sample = PERSIST_NODE_TIMER.start();
|
||||
|
||||
try {
|
||||
final Tags tags = Tags.of("node", node.getUri().getHost());
|
||||
|
||||
return messagesCache.getQueues(node, scanCount)
|
||||
.filter(_ -> dynamicConfigurationManager.getConfiguration().getMessagePersisterConfiguration()
|
||||
.isPersistenceEnabled())
|
||||
.flatMap(queueKey -> Mono.defer(() -> shouldPersistQueue(queueKey))
|
||||
.retryWhen(retryBackoffSpec)
|
||||
.onErrorResume(e -> {
|
||||
logger.warn("Failed to determine whether queue {} should be persisted", queueKey, e);
|
||||
return Mono.empty();
|
||||
})
|
||||
.mapNotNull(shouldPersist -> shouldPersist ? queueKey : null)
|
||||
.doOnTerminate(() -> Metrics.counter(INSPECTED_QUEUE_COUNTER_NAME, tags).increment()), maxConcurrency)
|
||||
.distinct()
|
||||
.flatMap(queueKey -> {
|
||||
final UUID accountIdentifier = MessagesCache.getAccountUuidFromQueueName(queueKey);
|
||||
final byte deviceId = MessagesCache.getDeviceIdFromQueueName(queueKey);
|
||||
|
||||
return Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(accountIdentifier))
|
||||
.map(maybeAccount -> maybeAccount
|
||||
.flatMap(account -> account.getDevice(deviceId))
|
||||
.map(device -> Tuples.of(maybeAccount.get(), device)))
|
||||
.flatMap(Mono::justOrEmpty)
|
||||
.retryWhen(retryBackoffSpec)
|
||||
.onErrorResume(e -> {
|
||||
logger.warn("Failed to fetch account/device for queue: {}", queueKey, e);
|
||||
return Mono.empty();
|
||||
});
|
||||
}, maxConcurrency)
|
||||
.flatMap(accountAndDevice -> {
|
||||
final Account account = accountAndDevice.getT1();
|
||||
final Device device = accountAndDevice.getT2();
|
||||
|
||||
return persistQueue(account, device, tags)
|
||||
.thenReturn(1)
|
||||
.retryWhen(retryBackoffSpec
|
||||
// Don't retry with backoff for persistence exceptions
|
||||
.filter(e -> !(e instanceof MessagePersistenceException)))
|
||||
.onErrorResume(e -> {
|
||||
logger.warn("Failed to persist queue {}::{} ({}); will schedule for retry",
|
||||
account.getIdentifier(IdentityType.ACI), device.getId(), node.getUri().getHost(), e);
|
||||
|
||||
return Mono.empty();
|
||||
});
|
||||
}, maxConcurrency)
|
||||
.onErrorResume(e -> {
|
||||
logger.warn("Unhandled error while persisting messages", e);
|
||||
return Mono.empty();
|
||||
})
|
||||
.count()
|
||||
.blockOptional()
|
||||
.map(Math::toIntExact)
|
||||
.orElse(0);
|
||||
} finally {
|
||||
sample.stop();
|
||||
PERSIST_NODE_COUNTER.increment();
|
||||
}
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
void persistQueue(final Account account, final Device device, final String shard) throws MessagePersistenceException {
|
||||
Mono<Void> persistQueue(final Account account, final Device device, final Tags baseTags) {
|
||||
final UUID accountUuid = account.getUuid();
|
||||
final byte deviceId = device.getId();
|
||||
|
||||
@@ -196,119 +277,128 @@ public class MessagePersister implements Managed {
|
||||
.orElse("unknown"));
|
||||
|
||||
final Timer.Sample sample = Timer.start();
|
||||
final Tags tags = baseTags.and(platformTag);
|
||||
|
||||
messagesCache.lockQueueForPersistence(accountUuid, deviceId);
|
||||
return Flux.usingWhen(
|
||||
messagesCache.lockQueueForPersistence(accountUuid, deviceId)
|
||||
.thenReturn(true),
|
||||
_ -> Flux.from(messagesCache.getMessagesToPersist(accountUuid, deviceId))
|
||||
.buffer(MESSAGE_BATCH_LIMIT)
|
||||
.flatMap(messages -> {
|
||||
final int urgentMessageCount = (int) messages.stream().filter(MessageProtos.Envelope::getUrgent).count();
|
||||
final int nonUrgentMessageCount = messages.size() - urgentMessageCount;
|
||||
|
||||
try {
|
||||
int messageCount = 0;
|
||||
List<MessageProtos.Envelope> messages;
|
||||
Metrics.counter(PERSISTED_MESSAGE_COUNTER_NAME, tags.and("urgent", "true")).increment(urgentMessageCount);
|
||||
Metrics.counter(PERSISTED_MESSAGE_COUNTER_NAME, tags.and("urgent", "false")).increment(nonUrgentMessageCount);
|
||||
Metrics.counter(PERSISTED_BYTES_COUNTER_NAME, tags)
|
||||
.increment(messages.stream().mapToInt(MessageProtos.Envelope::getSerializedSize).sum());
|
||||
|
||||
int consecutiveEmptyCacheRemovals = 0;
|
||||
return Mono.fromRunnable(() -> messagesManager.persistMessages(accountUuid, device, messages))
|
||||
.subscribeOn(persistQueueScheduler)
|
||||
.thenReturn(messages.size());
|
||||
}, 1)
|
||||
.reduce(0, Integer::sum)
|
||||
.onErrorResume(ItemCollectionSizeLimitExceededException.class, _ -> {
|
||||
final boolean isPrimary = deviceId == Device.PRIMARY_ID;
|
||||
Metrics.counter(OVERSIZED_QUEUE_COUNTER_NAME, "primary", String.valueOf(isPrimary)).increment();
|
||||
// may throw, in which case we'll retry later by the usual mechanism
|
||||
if (isPrimary) {
|
||||
logger.warn("Failed to persist queue {}::{} due to overfull queue; will trim oldest messages",
|
||||
account.getUuid(), deviceId);
|
||||
|
||||
do {
|
||||
messages = messagesCache.getMessagesToPersist(accountUuid, deviceId, MESSAGE_BATCH_LIMIT);
|
||||
return trimQueue(account, device)
|
||||
.then(Mono.error(new MessagePersistenceException("Could not persist due to an overfull queue. Trimmed primary queue, a subsequent retry may succeed")));
|
||||
} else {
|
||||
logger.warn("Failed to persist queue {}::{} due to overfull queue; will unlink device", accountUuid, deviceId);
|
||||
|
||||
final int urgentMessageCount = (int) messages.stream().filter(MessageProtos.Envelope::getUrgent).count();
|
||||
final int nonUrgentMessageCount = messages.size() - urgentMessageCount;
|
||||
|
||||
final Tags tags = Tags.of(platformTag, Tag.of("shard", shard));
|
||||
|
||||
Metrics.counter(PERSISTED_MESSAGE_COUNTER_NAME, tags.and("urgent", "true")).increment(urgentMessageCount);
|
||||
Metrics.counter(PERSISTED_MESSAGE_COUNTER_NAME, tags.and("urgent", "false")).increment(nonUrgentMessageCount);
|
||||
Metrics.counter(PERSISTED_BYTES_COUNTER_NAME, tags)
|
||||
.increment(messages.stream().mapToInt(MessageProtos.Envelope::getSerializedSize).sum());
|
||||
|
||||
int messagesRemovedFromCache = messagesManager.persistMessages(accountUuid, device, messages);
|
||||
messageCount += messages.size();
|
||||
|
||||
if (messagesRemovedFromCache == 0) {
|
||||
consecutiveEmptyCacheRemovals += 1;
|
||||
} else {
|
||||
consecutiveEmptyCacheRemovals = 0;
|
||||
}
|
||||
|
||||
if (consecutiveEmptyCacheRemovals > CONSECUTIVE_EMPTY_CACHE_REMOVAL_LIMIT) {
|
||||
throw new MessagePersistenceException("persistence failure loop detected");
|
||||
}
|
||||
|
||||
} while (!messages.isEmpty());
|
||||
|
||||
DistributionSummary.builder(QUEUE_SIZE_DISTRIBUTION_SUMMARY_NAME)
|
||||
.tags(Tags.of(platformTag))
|
||||
.register(Metrics.globalRegistry)
|
||||
.record(messageCount);
|
||||
} catch (ItemCollectionSizeLimitExceededException e) {
|
||||
final boolean isPrimary = deviceId == Device.PRIMARY_ID;
|
||||
Metrics.counter(OVERSIZED_QUEUE_COUNTER_NAME, "primary", String.valueOf(isPrimary)).increment();
|
||||
// may throw, in which case we'll retry later by the usual mechanism
|
||||
if (isPrimary) {
|
||||
logger.warn("Failed to persist queue {}::{} due to overfull queue; will trim oldest messages",
|
||||
account.getUuid(), deviceId);
|
||||
trimQueue(account, deviceId);
|
||||
throw new MessagePersistenceException("Could not persist due to an overfull queue. Trimmed primary queue, a subsequent retry may succeed");
|
||||
} else {
|
||||
logger.warn("Failed to persist queue {}::{} due to overfull queue; will unlink device", accountUuid, deviceId);
|
||||
accountsManager.removeDevice(account, deviceId);
|
||||
}
|
||||
} finally {
|
||||
messagesCache.unlockQueueForPersistence(accountUuid, deviceId);
|
||||
sample.stop(PERSIST_QUEUE_TIMER);
|
||||
}
|
||||
return Mono.fromRunnable(() -> accountsManager.removeDevice(account, deviceId))
|
||||
.subscribeOn(persistQueueScheduler)
|
||||
.then(Mono.empty());
|
||||
}
|
||||
})
|
||||
.doOnSuccess(messagesPersisted -> {
|
||||
if (messagesPersisted != null) {
|
||||
DistributionSummary.builder(QUEUE_SIZE_DISTRIBUTION_SUMMARY_NAME)
|
||||
.tags(Tags.of(platformTag))
|
||||
.register(Metrics.globalRegistry)
|
||||
.record(messagesPersisted);
|
||||
}
|
||||
})
|
||||
.doOnTerminate(() -> sample.stop(PERSIST_QUEUE_TIMER)),
|
||||
_ -> messagesCache.unlockQueueForPersistence(accountUuid, deviceId))
|
||||
.then();
|
||||
}
|
||||
|
||||
private void trimQueue(final Account account, byte deviceId) {
|
||||
private Mono<Void> trimQueue(final Account account, final Device device) {
|
||||
final UUID aci = account.getIdentifier(IdentityType.ACI);
|
||||
final byte deviceId = device.getId();
|
||||
|
||||
final Optional<Device> maybeDevice = account.getDevice(deviceId);
|
||||
if (maybeDevice.isEmpty()) {
|
||||
logger.warn("Not deleting messages for overfull queue {}::{}, deviceId {} does not exist",
|
||||
aci, deviceId, deviceId);
|
||||
return;
|
||||
}
|
||||
final Device device = maybeDevice.get();
|
||||
|
||||
// Calculate how many bytes we should trim
|
||||
final long cachedMessageBytes = messagesCache.estimatePersistedQueueSizeBytes(aci, deviceId).join();
|
||||
final double extraRoomRatio = this.dynamicConfigurationManager.getConfiguration()
|
||||
.getMessagePersisterConfiguration()
|
||||
.getTrimOversizedQueueExtraRoomRatio();
|
||||
final long targetDeleteBytes = Math.round(cachedMessageBytes * extraRoomRatio);
|
||||
|
||||
final AtomicLong oldestMessage = new AtomicLong(0L);
|
||||
final AtomicLong newestMessage = new AtomicLong(0L);
|
||||
final AtomicLong bytesDeleted = new AtomicLong(0L);
|
||||
|
||||
// Iterate from the oldest message until we've removed targetDeleteBytes
|
||||
final Pair<Long, Long> outcomes = Flux.from(messagesManager.getMessagesForDeviceReactive(aci, device, false))
|
||||
.concatMap(envelope -> {
|
||||
if (bytesDeleted.getAndAdd(envelope.getSerializedSize()) >= targetDeleteBytes) {
|
||||
return Mono.just(Optional.<MessageProtos.Envelope>empty());
|
||||
}
|
||||
oldestMessage.compareAndSet(0L, envelope.getServerTimestamp());
|
||||
newestMessage.set(envelope.getServerTimestamp());
|
||||
return Mono.just(Optional.of(envelope));
|
||||
})
|
||||
.takeWhile(Optional::isPresent)
|
||||
.flatMap(maybeEnvelope -> {
|
||||
final MessageProtos.Envelope envelope = maybeEnvelope.get();
|
||||
TRIMMED_MESSAGE_COUNTER.increment();
|
||||
TRIMMED_MESSAGE_BYTES_COUNTER.increment(envelope.getSerializedSize());
|
||||
return Mono
|
||||
.fromCompletionStage(() -> messagesManager
|
||||
.delete(aci, device, UUID.fromString(envelope.getServerGuid()), envelope.getServerTimestamp()))
|
||||
.retryWhen(Retry.backoff(5, Duration.ofSeconds(1)))
|
||||
.map(Optional::isPresent);
|
||||
})
|
||||
.reduce(Pair.of(0L, 0L), (acc, deleted) -> deleted
|
||||
? Pair.of(acc.getLeft() + 1, acc.getRight())
|
||||
: Pair.of(acc.getLeft(), acc.getRight() + 1))
|
||||
.block();
|
||||
final AtomicLong cachedMessageBytes = new AtomicLong(0L);
|
||||
final AtomicLong targetDeleteBytes = new AtomicLong(0L);
|
||||
|
||||
logger.warn(
|
||||
"Finished trimming {}:{}. Oldest message = {}, newest message = {}. Attempted to delete {} persisted bytes to make room for {} cached message bytes. Delete outcomes: {} present, {} missing.",
|
||||
aci, deviceId,
|
||||
Instant.ofEpochMilli(oldestMessage.get()), Instant.ofEpochMilli(newestMessage.get()),
|
||||
targetDeleteBytes, cachedMessageBytes,
|
||||
outcomes.getLeft(), outcomes.getRight());
|
||||
return Mono.fromFuture(() -> messagesCache.estimatePersistedQueueSizeBytes(aci, deviceId))
|
||||
.flatMap(estimatedPersistedQueueSize -> {
|
||||
cachedMessageBytes.set(estimatedPersistedQueueSize);
|
||||
targetDeleteBytes.set(Math.round(estimatedPersistedQueueSize * extraRoomRatio));
|
||||
|
||||
return Flux.from(messagesManager.getMessagesForDeviceReactive(aci, device, false))
|
||||
.concatMap(envelope -> {
|
||||
if (bytesDeleted.getAndAdd(envelope.getSerializedSize()) >= targetDeleteBytes.get()) {
|
||||
return Mono.just(Optional.<MessageProtos.Envelope>empty());
|
||||
}
|
||||
oldestMessage.compareAndSet(0L, envelope.getServerTimestamp());
|
||||
newestMessage.set(envelope.getServerTimestamp());
|
||||
return Mono.just(Optional.of(envelope));
|
||||
})
|
||||
.takeWhile(Optional::isPresent)
|
||||
.flatMap(maybeEnvelope -> {
|
||||
// We know this must be present because we `takeWhile` values are present
|
||||
final MessageProtos.Envelope envelope = maybeEnvelope.orElseThrow(AssertionError::new);
|
||||
TRIMMED_MESSAGE_COUNTER.increment();
|
||||
TRIMMED_MESSAGE_BYTES_COUNTER.increment(envelope.getSerializedSize());
|
||||
return Mono
|
||||
.fromCompletionStage(() -> messagesManager
|
||||
.delete(aci, device, UUID.fromString(envelope.getServerGuid()), envelope.getServerTimestamp()))
|
||||
.retryWhen(retryBackoffSpec)
|
||||
.map(Optional::isPresent);
|
||||
})
|
||||
.reduce(Pair.of(0L, 0L), (acc, deleted) -> deleted
|
||||
? Pair.of(acc.getLeft() + 1, acc.getRight())
|
||||
: Pair.of(acc.getLeft(), acc.getRight() + 1));
|
||||
})
|
||||
.doOnSuccess(outcomes -> {
|
||||
if (outcomes != null) {
|
||||
logger.warn(
|
||||
"Finished trimming {}:{}. Oldest message = {}, newest message = {}. Attempted to delete {} persisted bytes to make room for {} cached message bytes. Delete outcomes: {} present, {} missing.",
|
||||
aci, deviceId,
|
||||
Instant.ofEpochMilli(oldestMessage.get()), Instant.ofEpochMilli(newestMessage.get()),
|
||||
targetDeleteBytes, cachedMessageBytes,
|
||||
outcomes.getLeft(), outcomes.getRight());
|
||||
}
|
||||
})
|
||||
.then();
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
Mono<Boolean> shouldPersistQueue(final String queueKey) {
|
||||
return messagesCache.getEarliestUndeliveredTimestamp(
|
||||
MessagesCache.getAccountUuidFromQueueName(queueKey),
|
||||
MessagesCache.getDeviceIdFromQueueName(queueKey))
|
||||
.map(oldestMessageTimestamp ->
|
||||
Duration.between(Instant.ofEpochMilli(oldestMessageTimestamp), clock.instant()).compareTo(persistDelay) > 0)
|
||||
.switchIfEmpty(Mono.just(false));
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
String getPersisterId() {
|
||||
return persisterId;
|
||||
}
|
||||
}
|
||||
+106
-92
@@ -13,9 +13,12 @@ import com.google.protobuf.InvalidProtocolBufferException;
|
||||
import io.github.resilience4j.reactor.retry.RetryOperator;
|
||||
import io.lettuce.core.Limit;
|
||||
import io.lettuce.core.Range;
|
||||
import io.lettuce.core.ScanArgs;
|
||||
import io.lettuce.core.ScanStream;
|
||||
import io.lettuce.core.ScoredValue;
|
||||
import io.lettuce.core.ZAddArgs;
|
||||
import io.lettuce.core.SetArgs;
|
||||
import io.lettuce.core.cluster.SlotHash;
|
||||
import io.lettuce.core.cluster.models.partitions.RedisClusterNode;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
@@ -38,6 +41,7 @@ import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.stream.Collectors;
|
||||
import org.reactivestreams.Publisher;
|
||||
import org.signal.libsignal.protocol.SealedSenderMultiRecipientMessage;
|
||||
import org.signal.libsignal.protocol.ServiceId;
|
||||
@@ -48,9 +52,8 @@ import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import org.whispersystems.textsecuregcm.util.ResilienceUtil;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import org.whispersystems.textsecuregcm.util.RedisClusterUtil;
|
||||
import org.whispersystems.textsecuregcm.util.ResilienceUtil;
|
||||
import reactor.core.observability.micrometer.Micrometer;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
@@ -85,9 +88,6 @@ import reactor.core.scheduler.Schedulers;
|
||||
* <dt>{@code queueLockKey}</dt>
|
||||
* <dd>Used to indicate that a queue is being modified by the {@link MessagePersister} and that {@code get_items} should
|
||||
* return an empty list.</dd>
|
||||
* <dt>{@code queueTotalIndexKey}</dt>
|
||||
* <dd>A sorted set of all queues in a shard. A queue’s score is the timestamp of its oldest message, which is used by
|
||||
* the {@link MessagePersister} to prioritize queues to persist.</dd>
|
||||
* </dl>
|
||||
* <p>
|
||||
* At a high level, the process is:
|
||||
@@ -127,15 +127,15 @@ public class MessagesCache {
|
||||
private final MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript insertMrmScript;
|
||||
private final MessagesCacheRemoveByGuidScript removeByGuidScript;
|
||||
private final MessagesCacheGetItemsScript getItemsScript;
|
||||
private final MessagesCacheReleaseNodeClaimScript releaseNodeClaimScript;
|
||||
private final MessagesCacheRemoveQueueScript removeQueueScript;
|
||||
private final MessagesCacheGetQueuesToPersistScript getQueuesToPersistScript;
|
||||
private final MessagesCacheRemoveRecipientViewFromMrmDataScript removeRecipientViewFromMrmDataScript;
|
||||
private final MessagesCacheUnlockQueueScript unlockQueueScript;
|
||||
|
||||
private int nextNodeRotateDistance = 0;
|
||||
|
||||
private final Timer insertTimer = Metrics.timer(name(MessagesCache.class, "insert"));
|
||||
private final Timer insertSharedMrmPayloadTimer = Metrics.timer(name(MessagesCache.class, "insertSharedMrmPayload"));
|
||||
private final Timer getMessagesTimer = Metrics.timer(name(MessagesCache.class, "get"));
|
||||
private final Timer getQueuesToPersistTimer = Metrics.timer(name(MessagesCache.class, "getQueuesToPersist"));
|
||||
private final Timer removeByGuidTimer = Metrics.timer(name(MessagesCache.class, "removeByGuid"));
|
||||
private final Timer removeRecipientViewTimer = Metrics.timer(name(MessagesCache.class, "removeRecipientView"));
|
||||
private final Timer clearQueueTimer = Metrics.timer(name(MessagesCache.class, "clear"));
|
||||
@@ -154,7 +154,6 @@ public class MessagesCache {
|
||||
|
||||
static final String RETRY_NAME = ResilienceUtil.name(MessagesCache.class);
|
||||
|
||||
static final String NEXT_SLOT_TO_PERSIST_KEY = "user_queue_persist_slot";
|
||||
private static final byte[] LOCK_VALUE = "1".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
@VisibleForTesting
|
||||
@@ -164,7 +163,9 @@ public class MessagesCache {
|
||||
static final Duration MAX_EPHEMERAL_MESSAGE_DELAY = Duration.ofSeconds(10);
|
||||
|
||||
private static final String GET_FLUX_NAME = MetricsUtil.name(MessagesCache.class, "get");
|
||||
private static final int PAGE_SIZE = 100;
|
||||
|
||||
@VisibleForTesting
|
||||
static final int PAGE_SIZE = 100;
|
||||
|
||||
private static final int REMOVE_MRM_RECIPIENT_VIEW_CONCURRENCY = 8;
|
||||
|
||||
@@ -187,9 +188,9 @@ public class MessagesCache {
|
||||
new MessagesCacheInsertScript(redisCluster, retryExecutor),
|
||||
new MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript(redisCluster, retryExecutor),
|
||||
new MessagesCacheGetItemsScript(redisCluster),
|
||||
new MessagesCacheReleaseNodeClaimScript(redisCluster),
|
||||
new MessagesCacheRemoveByGuidScript(redisCluster, retryExecutor),
|
||||
new MessagesCacheRemoveQueueScript(redisCluster),
|
||||
new MessagesCacheGetQueuesToPersistScript(redisCluster),
|
||||
new MessagesCacheRemoveRecipientViewFromMrmDataScript(redisCluster),
|
||||
new MessagesCacheUnlockQueueScript(redisCluster)
|
||||
);
|
||||
@@ -202,9 +203,10 @@ public class MessagesCache {
|
||||
final ExperimentEnrollmentManager experimentEnrollmentManager,
|
||||
final MessagesCacheInsertScript insertScript,
|
||||
final MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript insertMrmScript,
|
||||
final MessagesCacheGetItemsScript getItemsScript, final MessagesCacheRemoveByGuidScript removeByGuidScript,
|
||||
final MessagesCacheGetItemsScript getItemsScript,
|
||||
final MessagesCacheReleaseNodeClaimScript releaseNodeClaimScript,
|
||||
final MessagesCacheRemoveByGuidScript removeByGuidScript,
|
||||
final MessagesCacheRemoveQueueScript removeQueueScript,
|
||||
final MessagesCacheGetQueuesToPersistScript getQueuesToPersistScript,
|
||||
final MessagesCacheRemoveRecipientViewFromMrmDataScript removeRecipientViewFromMrmDataScript,
|
||||
final MessagesCacheUnlockQueueScript unlockQueueScript) throws IOException {
|
||||
|
||||
@@ -220,8 +222,8 @@ public class MessagesCache {
|
||||
this.insertMrmScript = insertMrmScript;
|
||||
this.removeByGuidScript = removeByGuidScript;
|
||||
this.getItemsScript = getItemsScript;
|
||||
this.releaseNodeClaimScript = releaseNodeClaimScript;
|
||||
this.removeQueueScript = removeQueueScript;
|
||||
this.getQueuesToPersistScript = getQueuesToPersistScript;
|
||||
this.removeRecipientViewFromMrmDataScript = removeRecipientViewFromMrmDataScript;
|
||||
this.unlockQueueScript = unlockQueueScript;
|
||||
}
|
||||
@@ -307,13 +309,30 @@ public class MessagesCache {
|
||||
.toCompletableFuture();
|
||||
}
|
||||
|
||||
public Publisher<MessageProtos.Envelope> get(final UUID destinationUuid, final byte destinationDevice) {
|
||||
public Publisher<MessageProtos.Envelope> get(final UUID destinationUuid, final byte destinationDeviceId) {
|
||||
return get(destinationUuid,
|
||||
destinationDeviceId,
|
||||
clock.instant().minus(MAX_EPHEMERAL_MESSAGE_DELAY),
|
||||
false);
|
||||
}
|
||||
|
||||
final long earliestAllowableEphemeralTimestamp =
|
||||
clock.millis() - MAX_EPHEMERAL_MESSAGE_DELAY.toMillis();
|
||||
Publisher<MessageProtos.Envelope> getMessagesToPersist(final UUID accountUuid, final byte destinationDeviceId) {
|
||||
return Flux.from(get(accountUuid,
|
||||
destinationDeviceId,
|
||||
// Discard all ephemeral messages when persisting
|
||||
Instant.ofEpochMilli(Long.MAX_VALUE),
|
||||
true));
|
||||
}
|
||||
|
||||
final Flux<MessageProtos.Envelope> allMessages = getAllMessages(destinationUuid, destinationDevice,
|
||||
earliestAllowableEphemeralTimestamp, PAGE_SIZE)
|
||||
private Publisher<MessageProtos.Envelope> get(final UUID destinationUuid,
|
||||
final byte destinationDeviceId,
|
||||
final Instant earliestAllowableEphemeralTimestamp,
|
||||
final boolean bypassLock) {
|
||||
|
||||
final long earliestAllowableEphemeralTimestampMillis = earliestAllowableEphemeralTimestamp.toEpochMilli();
|
||||
|
||||
final Flux<MessageProtos.Envelope> allMessages = getAllMessages(destinationUuid, destinationDeviceId,
|
||||
earliestAllowableEphemeralTimestampMillis, PAGE_SIZE, bypassLock)
|
||||
.publish()
|
||||
// We expect exactly three subscribers to this base flux:
|
||||
// 1. the websocket that delivers messages to clients
|
||||
@@ -325,25 +344,41 @@ public class MessagesCache {
|
||||
|
||||
final Flux<MessageProtos.Envelope> messagesToPublish = allMessages
|
||||
.filter(Predicate.not(envelope ->
|
||||
isStaleEphemeralMessage(envelope, earliestAllowableEphemeralTimestamp) || isStaleMrmMessage(envelope)));
|
||||
isStaleEphemeralMessage(envelope, earliestAllowableEphemeralTimestampMillis) || isStaleMrmMessage(envelope)));
|
||||
|
||||
final Flux<MessageProtos.Envelope> staleEphemeralMessages = allMessages
|
||||
.filter(envelope -> isStaleEphemeralMessage(envelope, earliestAllowableEphemeralTimestamp));
|
||||
discardStaleMessages(destinationUuid, destinationDevice, staleEphemeralMessages, staleEphemeralMessagesCounter, "ephemeral");
|
||||
.filter(envelope -> isStaleEphemeralMessage(envelope, earliestAllowableEphemeralTimestampMillis));
|
||||
discardStaleMessages(destinationUuid, destinationDeviceId, staleEphemeralMessages, staleEphemeralMessagesCounter, "ephemeral");
|
||||
|
||||
final Flux<MessageProtos.Envelope> staleMrmMessages = allMessages.filter(MessagesCache::isStaleMrmMessage)
|
||||
// clearing the sharedMrmKey prevents unnecessary calls to update the shared MRM data
|
||||
.map(envelope -> envelope.toBuilder().clearSharedMrmKey().build());
|
||||
discardStaleMessages(destinationUuid, destinationDevice, staleMrmMessages, staleMrmMessagesCounter, "mrm");
|
||||
discardStaleMessages(destinationUuid, destinationDeviceId, staleMrmMessages, staleMrmMessagesCounter, "mrm");
|
||||
|
||||
return messagesToPublish.name(GET_FLUX_NAME)
|
||||
.tap(Micrometer.metrics(Metrics.globalRegistry));
|
||||
}
|
||||
|
||||
public Mono<Long> getEarliestUndeliveredTimestamp(final UUID destinationUuid, final byte destinationDevice) {
|
||||
return getAllMessages(destinationUuid, destinationDevice, -1, 1)
|
||||
/// Returns the server-issued timestamp of the earliest message in the queue for the given account/device, regardless
|
||||
/// of the type of message. Note that this method may return a timestamp for a message that would ultimately be
|
||||
/// discarded were a caller to actually fetch messages (i.e. an expired ephemeral message).
|
||||
///
|
||||
/// @param destinationUuid the account identifier for the queue for which to get a timestamp
|
||||
/// @param destinationDeviceId the device identifier for the queue for which to get a timestamp
|
||||
///
|
||||
/// @return a `Mono` that publishes the timestamp (in milliseconds since the epoch) of the earliest message in the
|
||||
/// given queue or yields no value if the queue is empty or does not exist
|
||||
public Mono<Long> getEarliestUndeliveredTimestamp(final UUID destinationUuid, final byte destinationDeviceId) {
|
||||
return redisCluster.withBinaryCluster(connection ->
|
||||
connection.reactive().zrange(getMessageQueueKey(destinationUuid, destinationDeviceId), 0, 0))
|
||||
.next()
|
||||
.map(MessageProtos.Envelope::getServerTimestamp);
|
||||
.flatMap(serializedEnvelope -> {
|
||||
try {
|
||||
return Mono.just(parseEnvelope(serializedEnvelope).getServerTimestamp());
|
||||
} catch (final InvalidProtocolBufferException e) {
|
||||
return Mono.error(e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static boolean isStaleEphemeralMessage(final MessageProtos.Envelope message,
|
||||
@@ -373,18 +408,21 @@ public class MessagesCache {
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
Flux<MessageProtos.Envelope> getAllMessages(final UUID destinationUuid, final byte destinationDevice,
|
||||
final long earliestAllowableEphemeralTimestamp, final int pageSize) {
|
||||
Flux<MessageProtos.Envelope> getAllMessages(final UUID destinationUuid,
|
||||
final byte destinationDevice,
|
||||
final long earliestAllowableEphemeralTimestamp,
|
||||
final int pageSize,
|
||||
final boolean bypassLock) {
|
||||
|
||||
// fetch messages by page
|
||||
return getNextMessagePage(destinationUuid, destinationDevice, -1, pageSize)
|
||||
return getNextMessagePage(destinationUuid, destinationDevice, -1, pageSize, bypassLock)
|
||||
.expand(queueItemsAndLastMessageId -> {
|
||||
// expand() is breadth-first, so each page will be published in order
|
||||
if (queueItemsAndLastMessageId.first().isEmpty()) {
|
||||
return Mono.empty();
|
||||
}
|
||||
|
||||
return getNextMessagePage(destinationUuid, destinationDevice, queueItemsAndLastMessageId.second(), pageSize);
|
||||
return getNextMessagePage(destinationUuid, destinationDevice, queueItemsAndLastMessageId.second(), pageSize, bypassLock);
|
||||
})
|
||||
.limitRate(1)
|
||||
// we want to ensure we don’t accidentally block the Lettuce/netty i/o executors
|
||||
@@ -529,10 +567,13 @@ public class MessagesCache {
|
||||
.subscribe();
|
||||
}
|
||||
|
||||
private Mono<Pair<List<byte[]>, Long>> getNextMessagePage(final UUID destinationUuid, final byte destinationDevice,
|
||||
long messageId, int pageSize) {
|
||||
private Mono<Pair<List<byte[]>, Long>> getNextMessagePage(final UUID destinationUuid,
|
||||
final byte destinationDevice,
|
||||
final long messageId,
|
||||
final int pageSize,
|
||||
final boolean bypassLock) {
|
||||
|
||||
return getItemsScript.execute(destinationUuid, destinationDevice, pageSize, messageId)
|
||||
return getItemsScript.execute(destinationUuid, destinationDevice, pageSize, messageId, bypassLock)
|
||||
.map(queueItems -> {
|
||||
logger.trace("Processing page: {}", messageId);
|
||||
|
||||
@@ -583,35 +624,6 @@ public class MessagesCache {
|
||||
.toFuture();
|
||||
}
|
||||
|
||||
List<MessageProtos.Envelope> getMessagesToPersist(final UUID accountUuid, final byte destinationDevice,
|
||||
final int limit) {
|
||||
|
||||
final Timer.Sample sample = Timer.start();
|
||||
|
||||
final List<byte[]> messages = redisCluster.withBinaryCluster(connection ->
|
||||
connection.sync().zrange(getMessageQueueKey(accountUuid, destinationDevice), 0, limit));
|
||||
|
||||
final Flux<MessageProtos.Envelope> allMessages = parseAndFetchMrms(Flux.fromIterable(messages), destinationDevice);
|
||||
|
||||
final Flux<MessageProtos.Envelope> messagesToPersist = allMessages
|
||||
.filter(Predicate.not(envelope ->
|
||||
envelope.getEphemeral() || isStaleMrmMessage(envelope)));
|
||||
|
||||
final Flux<MessageProtos.Envelope> ephemeralMessages = allMessages
|
||||
.filter(MessageProtos.Envelope::getEphemeral);
|
||||
discardStaleMessages(accountUuid, destinationDevice, ephemeralMessages, staleEphemeralMessagesCounter, "ephemeral");
|
||||
|
||||
final Flux<MessageProtos.Envelope> staleMrmMessages = allMessages.filter(MessagesCache::isStaleMrmMessage)
|
||||
// clearing the sharedMrmKey prevents unnecessary calls to update the shared MRM data
|
||||
.map(envelope -> envelope.toBuilder().clearSharedMrmKey().build());
|
||||
discardStaleMessages(accountUuid, destinationDevice, staleMrmMessages, staleMrmMessagesCounter, "mrm");
|
||||
|
||||
return messagesToPersist
|
||||
.collectList()
|
||||
.doOnTerminate(() -> sample.stop(getMessagesTimer))
|
||||
.block(Duration.ofSeconds(5));
|
||||
}
|
||||
|
||||
private Flux<MessageProtos.Envelope> parseAndFetchMrms(final Flux<byte[]> serializedMessages, final byte destinationDevice) {
|
||||
return serializedMessages
|
||||
.mapNotNull(message -> {
|
||||
@@ -680,37 +692,47 @@ public class MessagesCache {
|
||||
.thenRun(() -> sample.stop(clearQueueTimer));
|
||||
}
|
||||
|
||||
public String shardForSlot(int slot) {
|
||||
try {
|
||||
return redisCluster.withBinaryCluster(
|
||||
connection -> connection.getPartitions().getPartitionBySlot(slot).getUri().getHost());
|
||||
} catch (final Throwable _) {
|
||||
return "unknown";
|
||||
}
|
||||
Optional<RedisClusterNode> claimNextNodeToPersist(final String persisterId, final Duration ttl) {
|
||||
final List<RedisClusterNode> primaryNodes = redisCluster.withCluster(connection -> connection.getPartitions().stream()
|
||||
.filter(node -> node.is(RedisClusterNode.NodeFlag.UPSTREAM))
|
||||
.collect(Collectors.toCollection(ArrayList::new)));
|
||||
|
||||
Collections.rotate(primaryNodes, Math.abs(nextNodeRotateDistance++) % primaryNodes.size());
|
||||
|
||||
return primaryNodes.stream()
|
||||
.filter(node -> claimNode(node, persisterId, ttl))
|
||||
.findFirst();
|
||||
}
|
||||
|
||||
int getNextSlotToPersist() {
|
||||
return (int) (redisCluster.withCluster(connection -> connection.sync().incr(NEXT_SLOT_TO_PERSIST_KEY))
|
||||
% SlotHash.SLOT_COUNT);
|
||||
@VisibleForTesting
|
||||
boolean claimNode(final RedisClusterNode node, final String persisterId, final Duration claimTtl) {
|
||||
return redisCluster.withCluster(connection ->
|
||||
"OK".equals(connection.sync().set(getPersisterNodeClaimKey(node), persisterId, SetArgs.Builder.nx().ex(claimTtl))));
|
||||
}
|
||||
|
||||
List<String> getQueuesToPersist(final int slot, final Instant maxTime, final int limit) {
|
||||
return getQueuesToPersistTimer.record(() -> getQueuesToPersistScript.execute(slot, maxTime, limit));
|
||||
void releaseNodeClaim(final RedisClusterNode node, final String persisterId) {
|
||||
releaseNodeClaimScript.execute(node, persisterId);
|
||||
}
|
||||
|
||||
void addQueueToPersist(final UUID accountUuid, final byte deviceId) {
|
||||
redisCluster.useBinaryCluster(connection -> connection.sync()
|
||||
.zadd(getQueueIndexKey(accountUuid, deviceId), ZAddArgs.Builder.nx(), System.currentTimeMillis(),
|
||||
getMessageQueueKey(accountUuid, deviceId)));
|
||||
@VisibleForTesting
|
||||
static String getPersisterNodeClaimKey(final RedisClusterNode node) {
|
||||
return "persister_node_claim::" + node.getNodeId();
|
||||
}
|
||||
|
||||
void lockQueueForPersistence(final UUID accountUuid, final byte deviceId) {
|
||||
redisCluster.useBinaryCluster(
|
||||
connection -> connection.sync().setex(getPersistInProgressKey(accountUuid, deviceId), 30, LOCK_VALUE));
|
||||
Flux<String> getQueues(final RedisClusterNode node, final int scanCount) {
|
||||
return redisCluster.withCluster(connection ->
|
||||
ScanStream.scan(connection.getConnection(node.getNodeId()).reactive(),
|
||||
ScanArgs.Builder.matches("user_queue::*").limit(scanCount)));
|
||||
}
|
||||
|
||||
void unlockQueueForPersistence(final UUID accountUuid, final byte deviceId) {
|
||||
unlockQueueScript.execute(accountUuid, deviceId);
|
||||
Mono<Void> lockQueueForPersistence(final UUID accountUuid, final byte deviceId) {
|
||||
return redisCluster.withBinaryCluster(
|
||||
connection -> connection.reactive().setex(getPersistInProgressKey(accountUuid, deviceId), 30, LOCK_VALUE))
|
||||
.then();
|
||||
}
|
||||
|
||||
Mono<Void> unlockQueueForPersistence(final UUID accountUuid, final byte deviceId) {
|
||||
return unlockQueueScript.execute(accountUuid, deviceId);
|
||||
}
|
||||
|
||||
static byte[] getMessageQueueKey(final UUID accountUuid, final byte deviceId) {
|
||||
@@ -721,14 +743,6 @@ public class MessagesCache {
|
||||
return ("user_queue_metadata::{" + accountUuid.toString() + "::" + deviceId + "}").getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
static byte[] getQueueIndexKey(final UUID accountUuid, final byte deviceId) {
|
||||
return getQueueIndexKey(SlotHash.getSlot(accountUuid.toString() + "::" + deviceId));
|
||||
}
|
||||
|
||||
static byte[] getQueueIndexKey(final int slot) {
|
||||
return ("user_queue_index::{" + RedisClusterUtil.getMinimalHashTag(slot) + "}").getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
static byte[] getSharedMrmKey(final UUID mrmGuid) {
|
||||
return ("mrm::{" + mrmGuid.toString() + "}").getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
+8
-3
@@ -28,15 +28,20 @@ class MessagesCacheGetItemsScript {
|
||||
this.getItemsScript = ClusterLuaScript.fromResource(redisCluster, "lua/get_items.lua", ScriptOutputType.OBJECT);
|
||||
}
|
||||
|
||||
Mono<List<byte[]>> execute(final UUID destinationUuid, final byte destinationDevice,
|
||||
int limit, long afterMessageId) {
|
||||
Mono<List<byte[]>> execute(final UUID destinationUuid,
|
||||
final byte destinationDevice,
|
||||
final int limit,
|
||||
final long afterMessageId,
|
||||
final boolean bypassLock) {
|
||||
|
||||
final List<byte[]> keys = List.of(
|
||||
MessagesCache.getMessageQueueKey(destinationUuid, destinationDevice), // queueKey
|
||||
MessagesCache.getPersistInProgressKey(destinationUuid, destinationDevice) // queueLockKey
|
||||
);
|
||||
final List<byte[]> args = List.of(
|
||||
String.valueOf(limit).getBytes(StandardCharsets.UTF_8), // limit
|
||||
String.valueOf(afterMessageId).getBytes(StandardCharsets.UTF_8) // afterMessageId
|
||||
String.valueOf(afterMessageId).getBytes(StandardCharsets.UTF_8), // afterMessageId
|
||||
String.valueOf(bypassLock).getBytes(StandardCharsets.UTF_8) // bypassLock
|
||||
);
|
||||
//noinspection unchecked
|
||||
return getItemsScript.executeBinaryReactive(keys, args)
|
||||
|
||||
-43
@@ -1,43 +0,0 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import io.lettuce.core.ScriptOutputType;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
|
||||
/**
|
||||
* Returns a list of queues that may be persisted. They will be sorted from oldest to more recent, limited by the
|
||||
* {@code maxTime} argument.
|
||||
*
|
||||
* @see MessagePersister
|
||||
*/
|
||||
class MessagesCacheGetQueuesToPersistScript {
|
||||
|
||||
private final ClusterLuaScript getQueuesToPersistScript;
|
||||
|
||||
MessagesCacheGetQueuesToPersistScript(final FaultTolerantRedisClusterClient redisCluster) throws IOException {
|
||||
this.getQueuesToPersistScript = ClusterLuaScript.fromResource(redisCluster, "lua/get_queues_to_persist.lua",
|
||||
ScriptOutputType.MULTI);
|
||||
}
|
||||
|
||||
List<String> execute(final int slot, final Instant maxTime, final int limit) {
|
||||
final List<String> keys = List.of(
|
||||
new String(MessagesCache.getQueueIndexKey(slot), StandardCharsets.UTF_8) // queueTotalIndexKey
|
||||
);
|
||||
final List<String> args = List.of(
|
||||
String.valueOf(maxTime.toEpochMilli()), // maxTime
|
||||
String.valueOf(limit) // limit
|
||||
);
|
||||
|
||||
//noinspection unchecked
|
||||
return (List<String>) getQueuesToPersistScript.execute(keys, args);
|
||||
}
|
||||
}
|
||||
-2
@@ -58,13 +58,11 @@ class MessagesCacheInsertScript {
|
||||
final List<byte[]> keys = List.of(
|
||||
MessagesCache.getMessageQueueKey(destinationUuid, destinationDevice), // queueKey
|
||||
MessagesCache.getMessageQueueMetadataKey(destinationUuid, destinationDevice), // queueMetadataKey
|
||||
MessagesCache.getQueueIndexKey(destinationUuid, destinationDevice), // queueTotalIndexKey
|
||||
RedisMessageAvailabilityManager.getClientEventChannel(destinationUuid, destinationDevice) // eventChannelKey
|
||||
);
|
||||
|
||||
final List<byte[]> args = new ArrayList<>(Arrays.asList(
|
||||
EnvelopeUtil.compress(envelope).toByteArray(), // message
|
||||
String.valueOf(envelope.getServerTimestamp()).getBytes(StandardCharsets.UTF_8), // currentTime
|
||||
envelope.getServerGuid().getBytes(StandardCharsets.UTF_8), // guid
|
||||
NEW_MESSAGE_EVENT_BYTES // eventPayload
|
||||
));
|
||||
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import io.lettuce.core.ScriptOutputType;
|
||||
import io.lettuce.core.cluster.models.partitions.RedisClusterNode;
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import org.whispersystems.textsecuregcm.util.ResilienceUtil;
|
||||
|
||||
class MessagesCacheReleaseNodeClaimScript {
|
||||
|
||||
private final ClusterLuaScript releaseNodeClaimScript;
|
||||
|
||||
MessagesCacheReleaseNodeClaimScript(final FaultTolerantRedisClusterClient redisCluster) throws IOException {
|
||||
this.releaseNodeClaimScript =
|
||||
ClusterLuaScript.fromResource(redisCluster, "lua/release_node_claim.lua", ScriptOutputType.STATUS);
|
||||
}
|
||||
|
||||
void execute(final RedisClusterNode node, final String persisterId) {
|
||||
final List<String> keys = List.of(MessagesCache.getPersisterNodeClaimKey(node));
|
||||
final List<String> arguments = List.of(persisterId);
|
||||
|
||||
ResilienceUtil.getGeneralRedisRetry(getClass().getSimpleName())
|
||||
.executeRunnable(() -> releaseNodeClaimScript.execute(keys, arguments));
|
||||
}
|
||||
}
|
||||
+1
-2
@@ -37,8 +37,7 @@ class MessagesCacheRemoveByGuidScript {
|
||||
|
||||
final List<byte[]> keys = List.of(
|
||||
MessagesCache.getMessageQueueKey(destinationUuid, destinationDevice), // queueKey
|
||||
MessagesCache.getMessageQueueMetadataKey(destinationUuid, destinationDevice), // queueMetadataKey
|
||||
MessagesCache.getQueueIndexKey(destinationUuid, destinationDevice) // queueTotalIndexKey
|
||||
MessagesCache.getMessageQueueMetadataKey(destinationUuid, destinationDevice) // queueMetadataKey
|
||||
);
|
||||
final List<byte[]> args = messageGuids.stream().map(guid -> guid.toString().getBytes(StandardCharsets.UTF_8))
|
||||
.toList();
|
||||
|
||||
+1
-2
@@ -39,8 +39,7 @@ class MessagesCacheRemoveQueueScript {
|
||||
|
||||
final List<byte[]> keys = List.of(
|
||||
MessagesCache.getMessageQueueKey(destinationUuid, destinationDevice), // queueKey
|
||||
MessagesCache.getMessageQueueMetadataKey(destinationUuid, destinationDevice), // queueMetadataKey
|
||||
MessagesCache.getQueueIndexKey(destinationUuid, destinationDevice) // queueTotalIndexKey
|
||||
MessagesCache.getMessageQueueMetadataKey(destinationUuid, destinationDevice) // queueMetadataKey
|
||||
);
|
||||
|
||||
final List<byte[]> args = new ArrayList<>();
|
||||
|
||||
+10
-7
@@ -6,15 +6,17 @@
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import io.lettuce.core.ScriptOutputType;
|
||||
import java.io.IOException;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import org.whispersystems.textsecuregcm.push.ClientEvent;
|
||||
import org.whispersystems.textsecuregcm.push.MessagesPersistedEvent;
|
||||
import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager;
|
||||
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import org.whispersystems.textsecuregcm.util.ResilienceUtil;
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.util.retry.Retry;
|
||||
|
||||
/**
|
||||
* Unlocks a message queue for persistence/message retrieval.
|
||||
@@ -33,13 +35,14 @@ class MessagesCacheUnlockQueueScript {
|
||||
ClusterLuaScript.fromResource(redisCluster, "lua/unlock_queue.lua", ScriptOutputType.STATUS);
|
||||
}
|
||||
|
||||
void execute(final UUID accountIdentifier, final byte deviceId) {
|
||||
Mono<Void> execute(final UUID accountIdentifier, final byte deviceId) {
|
||||
final List<byte[]> keys = List.of(
|
||||
MessagesCache.getPersistInProgressKey(accountIdentifier, deviceId), // persistInProgressKey
|
||||
RedisMessageAvailabilityManager.getClientEventChannel(accountIdentifier, deviceId) // eventChannelKey
|
||||
);
|
||||
|
||||
ResilienceUtil.getGeneralRedisRetry(MessagesCache.RETRY_NAME)
|
||||
.executeRunnable(() -> unlockQueueScript.executeBinary(keys, MESSAGES_PERSISTED_EVENT_ARGS));
|
||||
return unlockQueueScript.executeBinaryReactive(keys, MESSAGES_PERSISTED_EVENT_ARGS)
|
||||
.retryWhen(Retry.backoff(3, Duration.ofSeconds(1)))
|
||||
.then();
|
||||
}
|
||||
}
|
||||
+18
-4
@@ -7,6 +7,7 @@ package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.DistributionSummary;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
@@ -71,6 +72,7 @@ public class PagedSingleUseKEMPreKeyStore {
|
||||
private final Timer deleteForDeviceTimer = Metrics.timer(name(getClass(), "deleteForDevice"));
|
||||
private final Timer deleteForAccountTimer = Metrics.timer(name(getClass(), "deleteForAccount"));
|
||||
|
||||
private final Counter outOfRangeKeysDiscarded = Metrics.counter(name(getClass(), "outOfRangeKeysDiscarded"));
|
||||
final DistributionSummary availableKeyCountDistributionSummary = DistributionSummary
|
||||
.builder(name(getClass(), "availableKeyCount"))
|
||||
.register(Metrics.globalRegistry);
|
||||
@@ -159,7 +161,14 @@ public class PagedSingleUseKEMPreKeyStore {
|
||||
*/
|
||||
public CompletableFuture<Optional<KEMSignedPreKey>> take(final UUID identifier, final byte deviceId) {
|
||||
final Timer.Sample sample = Timer.start();
|
||||
return takeHelper(identifier, deviceId)
|
||||
.whenComplete((maybeKey, throwable) ->
|
||||
sample.stop(Metrics.timer(
|
||||
takeKeyTimerName,
|
||||
KEY_PRESENT_TAG_NAME, String.valueOf(maybeKey != null && maybeKey.isPresent()))));
|
||||
}
|
||||
|
||||
private CompletableFuture<Optional<KEMSignedPreKey>> takeHelper(final UUID identifier, final byte deviceId) {
|
||||
return dynamoDbAsyncClient.updateItem(UpdateItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.key(Map.of(
|
||||
@@ -196,10 +205,15 @@ public class PagedSingleUseKEMPreKeyStore {
|
||||
.exceptionally(ExceptionUtils.exceptionallyHandler(
|
||||
ConditionalCheckFailedException.class,
|
||||
e -> Optional.empty()))
|
||||
.whenComplete((maybeKey, throwable) ->
|
||||
sample.stop(Metrics.timer(
|
||||
takeKeyTimerName,
|
||||
KEY_PRESENT_TAG_NAME, String.valueOf(maybeKey != null && maybeKey.isPresent()))));
|
||||
.thenCompose(maybeKey -> {
|
||||
if (!maybeKey.map(KEMSignedPreKey::keyId).map(KeyIdUtil::keyIdValid).orElse(true)) {
|
||||
// At some point we did not validate that keyIds fit in an unsigned 32-bit integer, which clients require.
|
||||
// This keyId was invalid, so just recursively fetch the next key
|
||||
outOfRangeKeysDiscarded.increment();
|
||||
return takeHelper(identifier, deviceId);
|
||||
}
|
||||
return CompletableFuture.completedFuture(maybeKey);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+23
-4
@@ -15,9 +15,12 @@ import java.io.IOException;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
import javax.annotation.Nullable;
|
||||
import io.lettuce.core.RedisFuture;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
@@ -35,6 +38,7 @@ public class ProfilesManager {
|
||||
private final Logger logger = LoggerFactory.getLogger(ProfilesManager.class);
|
||||
|
||||
private static final String CACHE_PREFIX = "profiles::";
|
||||
private static final String CACHE_PREFIX_V1 = "profiles_v1::";
|
||||
|
||||
private final Profiles profiles;
|
||||
private final FaultTolerantRedisClusterClient cacheCluster;
|
||||
@@ -145,6 +149,7 @@ public class ProfilesManager {
|
||||
final String profileJson = mapper.writeValueAsString(profile);
|
||||
|
||||
cacheCluster.useCluster(connection -> connection.sync().hset(getCacheKey(uuid), profile.version(), profileJson));
|
||||
cacheCluster.useBinaryCluster(connection -> connection.sync().hset(getCacheKeyV1(uuid), profile.version().getBytes(), profileJson.getBytes()));
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new IllegalArgumentException(e);
|
||||
}
|
||||
@@ -159,8 +164,11 @@ public class ProfilesManager {
|
||||
throw new IllegalArgumentException(e);
|
||||
}
|
||||
|
||||
return cacheCluster.withCluster(connection ->
|
||||
connection.async().hset(getCacheKey(uuid), profile.version(), profileJson))
|
||||
final RedisFuture<Boolean> oldSet = cacheCluster.withCluster(connection ->
|
||||
connection.async().hset(getCacheKey(uuid), profile.version(), profileJson));
|
||||
final RedisFuture<Boolean> newSet = cacheCluster.withBinaryCluster(connection ->
|
||||
connection.async().hset(getCacheKeyV1(uuid), profile.version().getBytes(), profileJson.getBytes()));
|
||||
return CompletableFuture.allOf(oldSet.toCompletableFuture(), newSet.toCompletableFuture())
|
||||
.thenRun(Util.NOOP)
|
||||
.toCompletableFuture();
|
||||
}
|
||||
@@ -200,9 +208,15 @@ public class ProfilesManager {
|
||||
}
|
||||
|
||||
private CompletableFuture<Void> redisDelete(UUID uuid) {
|
||||
|
||||
final Supplier<CompletionStage<Void>> deletesSupplier = () ->
|
||||
CompletableFuture.allOf(
|
||||
cacheCluster.withCluster(connection -> connection.async().del(getCacheKey(uuid))).toCompletableFuture(),
|
||||
cacheCluster.withBinaryCluster(connection -> connection.async().del(getCacheKeyV1(uuid)))
|
||||
.toCompletableFuture()
|
||||
);
|
||||
return ResilienceUtil.getGeneralRedisRetry(RETRY_NAME)
|
||||
.executeCompletionStage(retryExecutor,
|
||||
() -> cacheCluster.withCluster(connection -> connection.async().del(getCacheKey(uuid))))
|
||||
.executeCompletionStage(retryExecutor, deletesSupplier)
|
||||
.toCompletableFuture()
|
||||
.thenRun(Util.NOOP);
|
||||
}
|
||||
@@ -211,4 +225,9 @@ public class ProfilesManager {
|
||||
static String getCacheKey(UUID uuid) {
|
||||
return CACHE_PREFIX + uuid.toString();
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static byte[] getCacheKeyV1(UUID uuid) {
|
||||
return (CACHE_PREFIX_V1 + '{' + uuid.toString() + '}').getBytes();
|
||||
}
|
||||
}
|
||||
+7
-4
@@ -107,11 +107,14 @@ public abstract class RepeatedUseSignedPreKeyStore<K extends SignedPreKey<?>> {
|
||||
.build())
|
||||
.thenApply(response -> response.hasItem() ? Optional.of(getPreKeyFromItem(response.item())) : Optional.empty());
|
||||
|
||||
findFuture.whenComplete((maybeSignedPreKey, throwable) ->
|
||||
sample.stop(Metrics.timer(findKeyTimerName,
|
||||
"keyPresent", String.valueOf(maybeSignedPreKey != null && maybeSignedPreKey.isPresent()))));
|
||||
return findFuture.whenComplete((maybeSignedPreKey, throwable) -> {
|
||||
if (throwable == null && maybeSignedPreKey.map(k -> !KeyIdUtil.keyIdValid(k.keyId())).orElse(false)) {
|
||||
throw new IllegalStateException("Encountered an impossible invalid repeated use pre-key id of " + maybeSignedPreKey.get().keyId());
|
||||
}
|
||||
|
||||
return findFuture;
|
||||
sample.stop(Metrics.timer(findKeyTimerName,
|
||||
"keyPresent", String.valueOf(maybeSignedPreKey != null && maybeSignedPreKey.isPresent())));
|
||||
});
|
||||
}
|
||||
|
||||
protected static Map<String, AttributeValue> getPrimaryKey(final UUID identifier, final byte deviceId) {
|
||||
|
||||
+22
-7
@@ -47,7 +47,6 @@ import software.amazon.awssdk.services.dynamodb.model.ReturnValue;
|
||||
* may fall back to using the device's repeated-use ("last-resort") signed pre-key instead.
|
||||
*/
|
||||
public class SingleUseECPreKeyStore {
|
||||
|
||||
private final DynamoDbAsyncClient dynamoDbAsyncClient;
|
||||
private final String tableName;
|
||||
|
||||
@@ -58,12 +57,14 @@ public class SingleUseECPreKeyStore {
|
||||
private final Timer deleteForAccountTimer = Metrics.timer(name(getClass(), "deleteForAccount"));
|
||||
|
||||
private final Counter noKeyCountAvailableCounter = Metrics.counter(name(getClass(), "noKeyCountAvailable"));
|
||||
|
||||
private final Counter outOfRangeKeysDiscarded =
|
||||
Metrics.counter(name(getClass(), "outOfRangeKeysDiscarded"));
|
||||
final DistributionSummary keysConsideredForTakeDistributionSummary = DistributionSummary
|
||||
.builder(name(getClass(), "keysConsideredForTake"))
|
||||
.distributionStatisticExpiry(Duration.ofMinutes(10))
|
||||
.register(Metrics.globalRegistry);
|
||||
|
||||
|
||||
final DistributionSummary availableKeyCountDistributionSummary = DistributionSummary
|
||||
.builder(name(getClass(), "availableKeyCount"))
|
||||
.distributionStatisticExpiry(Duration.ofMinutes(10))
|
||||
@@ -135,7 +136,7 @@ public class SingleUseECPreKeyStore {
|
||||
public CompletableFuture<Optional<ECPreKey>> take(final UUID identifier, final byte deviceId) {
|
||||
final Timer.Sample sample = Timer.start();
|
||||
final AttributeValue partitionKey = getPartitionKey(identifier);
|
||||
final AtomicInteger keysConsidered = new AtomicInteger(0);
|
||||
final AtomicInteger deletionAttempts = new AtomicInteger(0);
|
||||
|
||||
return Flux.from(dynamoDbAsyncClient.queryPaginator(QueryRequest.builder()
|
||||
.tableName(tableName)
|
||||
@@ -156,16 +157,26 @@ public class SingleUseECPreKeyStore {
|
||||
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)
|
||||
.doOnNext(deleteItemResponse -> keysConsidered.incrementAndGet())
|
||||
.concatMap(deleteItemRequest -> Mono.fromFuture(() -> dynamoDbAsyncClient.deleteItem(deleteItemRequest)))
|
||||
.doOnNext(_ -> deletionAttempts.incrementAndGet())
|
||||
.filter(DeleteItemResponse::hasAttributes)
|
||||
.filter(item -> {
|
||||
final long keyId = getKeyIdFromItem(item.attributes());
|
||||
final boolean keyIdValid = KeyIdUtil.keyIdValid(keyId);
|
||||
if (!keyIdValid) {
|
||||
outOfRangeKeysDiscarded.increment();
|
||||
}
|
||||
// At some point we did not validate that keyIds fit in an unsigned 32-bit integer, which clients require.
|
||||
// If this keyId is invalid, we'll skip it and fetch the next key
|
||||
return keyIdValid;
|
||||
})
|
||||
.next()
|
||||
.map(deleteItemResponse -> getPreKeyFromItem(deleteItemResponse.attributes()))
|
||||
.toFuture()
|
||||
.thenApply(Optional::ofNullable)
|
||||
.whenComplete((maybeKey, throwable) -> {
|
||||
sample.stop(Metrics.timer(takeKeyTimerName, KEY_PRESENT_TAG_NAME, String.valueOf(maybeKey != null && maybeKey.isPresent())));
|
||||
keysConsideredForTakeDistributionSummary.record(keysConsidered.get());
|
||||
keysConsideredForTakeDistributionSummary.record(deletionAttempts.get());
|
||||
});
|
||||
}
|
||||
|
||||
@@ -310,7 +321,7 @@ public class SingleUseECPreKeyStore {
|
||||
}
|
||||
|
||||
private ECPreKey getPreKeyFromItem(final Map<String, AttributeValue> item) {
|
||||
final long keyId = item.get(KEY_DEVICE_ID_KEY_ID).b().asByteBuffer().getLong(8);
|
||||
final long keyId = getKeyIdFromItem(item);
|
||||
final byte[] publicKey = AttributeValues.extractByteArray(item.get(ATTR_PUBLIC_KEY), PARSE_BYTE_ARRAY_COUNTER_NAME);
|
||||
|
||||
try {
|
||||
@@ -320,4 +331,8 @@ public class SingleUseECPreKeyStore {
|
||||
throw new IllegalArgumentException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private static long getKeyIdFromItem(final Map<String, AttributeValue> item) {
|
||||
return item.get(KEY_DEVICE_ID_KEY_ID).b().asByteBuffer().getLong(8);
|
||||
}
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
public class UnexpectedExistingPhoneNumberException extends RuntimeException {
|
||||
}
|
||||
+3
-1
@@ -206,7 +206,9 @@ public class AppleDeviceCheckManager {
|
||||
}
|
||||
|
||||
// Store the updated sign count, so we can check the next assertion (step 6)
|
||||
appleDeviceChecks.updateCounter(account, keyId, appleDevice.getCounter());
|
||||
if (!appleDeviceChecks.updateCounter(account, keyId, appleDevice.getCounter())) {
|
||||
throw new RequestReuseException("Sign count from request less than stored sign count");
|
||||
}
|
||||
removeChallenge(redisChallengeKey);
|
||||
}
|
||||
|
||||
|
||||
+350
@@ -0,0 +1,350 @@
|
||||
package org.whispersystems.textsecuregcm.storage.foundationdb;
|
||||
|
||||
import com.apple.foundationdb.Database;
|
||||
import com.apple.foundationdb.KeySelector;
|
||||
import com.apple.foundationdb.StreamingMode;
|
||||
import com.apple.foundationdb.Transaction;
|
||||
import com.google.protobuf.InvalidProtocolBufferException;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.storage.MessageStreamEntry;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.FluxSink;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.function.BiConsumer;
|
||||
|
||||
/// Publishes a message stream from a device queue in FoundationDB. Capable of publishing both a finite stream for
|
||||
/// catching up to end-of-queue,and an infinite stream for live updates.
|
||||
class FoundationDbMessagePublisher {
|
||||
|
||||
private final Database database;
|
||||
private final MessageGuidCodec messageGuidCodec;
|
||||
/// The maximum number of messages we will fetch per range query operation to avoid excessive memory consumption
|
||||
private final int maxMessagesPerScan;
|
||||
/// The end key at which we stop reading messages. For finite publisher, this is just past the end-of-queue key at the
|
||||
/// time the publisher was created. For an infinite publisher, this is the end of subspace range.
|
||||
private final KeySelector endKeyExclusive;
|
||||
|
||||
/// Keeps track of the key from which to start reading on the next iteration
|
||||
private volatile KeySelector beginKeyCursor;
|
||||
|
||||
enum State {
|
||||
/// Messages are likely available in the queue. Initial state.
|
||||
MESSAGES_AVAILABLE,
|
||||
/// We're actively fetching messages from FoundationDB.
|
||||
FETCHING_MESSAGES,
|
||||
/// We have read all available messages in the queue.
|
||||
QUEUE_EMPTY,
|
||||
/// The message available watch triggered while other stuff was going on. We record it as a state so that we can
|
||||
/// fetch new messages at a more opportune time.
|
||||
MESSAGE_AVAILABLE_SIGNAL_BUFFERED,
|
||||
/// Waiting for the message available watch to trigger that signals new messages have arrived.
|
||||
AWAITING_NEW_MESSAGES,
|
||||
/// Terminal state indicating no more messages will be published. Either we have successfully published all messages
|
||||
/// in the case of a finite publisher, or the subscriber has indicated that it has terminated.
|
||||
TERMINATED,
|
||||
/// Terminal state reached when there is an error fetching or publishing messages.
|
||||
ERROR
|
||||
}
|
||||
|
||||
enum Event {
|
||||
/// Downstream subscriber requested more items.
|
||||
DEMAND_REQUESTED,
|
||||
/// The FoundationDB range query returned less than the batch size.
|
||||
FETCHED_ALL_AVAILABLE_MESSAGES,
|
||||
/// We have successfully fetched and published a message batch
|
||||
PUBLISHED_MESSAGES,
|
||||
/// The message available watch triggered indicating new messages have arrived.
|
||||
MESSAGE_AVAILABLE_WATCH_TRIGGERED,
|
||||
/// Internal self-trigger used to immediately transition to the next state.
|
||||
INTERNAL_TRIGGER,
|
||||
/// An error occurred during fetching from FoundationDB or publishing messages to the sink.
|
||||
FETCH_OR_PUBLISH_ERROR_OCCURRED
|
||||
}
|
||||
|
||||
/// The key that is updated whenever new messages are available in the queue. If null, it is inferred that the publisher
|
||||
/// is finite and will terminate when the end-of-queue at time of publisher creation is reached. Otherwise, the publisher
|
||||
/// is "infinite" and will continue to wait for new messages and publish them in a loop.
|
||||
@Nullable private final byte[] messagesAvailableWatchKey;
|
||||
/// Listener to watch for state machine transitions; used for testing.
|
||||
private final BiConsumer<State, State> stateChangeListener;
|
||||
private final Flux<MessageStreamEntry.Envelope> messagePublisher;
|
||||
/// Whether the publisher is finite or infinite.
|
||||
private final boolean terminateOnQueueEmpty;
|
||||
|
||||
/// Tracks the current state of the publisher state machine. Initial state presumes that messages are available in the queue.
|
||||
private State state = State.MESSAGES_AVAILABLE;
|
||||
/// Reference to the sink we publishes messages to.
|
||||
private volatile FluxSink<MessageStreamEntry.Envelope> emitter;
|
||||
/// Future that completes when the watch for {@link #messagesAvailableWatchKey} triggers.
|
||||
private CompletableFuture<Void> watchFuture;
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(FoundationDbMessagePublisher.class);
|
||||
|
||||
FoundationDbMessagePublisher(
|
||||
final KeySelector beginKeyInclusive,
|
||||
final KeySelector endKeyExclusive,
|
||||
final Database database,
|
||||
final MessageGuidCodec messageGuidCodec,
|
||||
final int maxMessagesPerScan,
|
||||
@Nullable final byte[] messagesAvailableWatchKey,
|
||||
@Nullable final BiConsumer<State, State> stateChangeListener) {
|
||||
|
||||
this.beginKeyCursor = beginKeyInclusive;
|
||||
this.endKeyExclusive = endKeyExclusive;
|
||||
this.database = database;
|
||||
this.messageGuidCodec = messageGuidCodec;
|
||||
this.maxMessagesPerScan = maxMessagesPerScan;
|
||||
this.messagesAvailableWatchKey = messagesAvailableWatchKey;
|
||||
this.terminateOnQueueEmpty = messagesAvailableWatchKey == null;
|
||||
this.stateChangeListener = stateChangeListener != null ? stateChangeListener : (_, _) -> {};
|
||||
this.messagePublisher = Flux.create(emitter -> {
|
||||
this.emitter = emitter;
|
||||
emitter.onRequest(_ -> transitionStateOnEvent(Event.DEMAND_REQUESTED));
|
||||
emitter.onDispose(this::onDispose);
|
||||
});
|
||||
}
|
||||
|
||||
/// Creates a [FoundationDbMessagePublisher] that publishes a stream of messages in a queue that terminates when it
|
||||
/// yields the last message that was present in the queue at the time the publisher was created. This is helpful in
|
||||
/// cases when callers need to "catch up" on stored messages without following fresh updates (for example, when a
|
||||
/// client first connects and needs to load stored messages before receiving a "live" stream of new messages).
|
||||
public static FoundationDbMessagePublisher createFinitePublisher(
|
||||
final KeySelector beginKeyInclusive,
|
||||
final KeySelector endKeyExclusive,
|
||||
final Database database,
|
||||
final MessageGuidCodec messageGuidCodec,
|
||||
final int maxMessagesPerScan) {
|
||||
|
||||
return new FoundationDbMessagePublisher(beginKeyInclusive,
|
||||
endKeyExclusive,
|
||||
database,
|
||||
messageGuidCodec,
|
||||
maxMessagesPerScan,
|
||||
null,
|
||||
null);
|
||||
}
|
||||
|
||||
/// Creates a [FoundationDbMessagePublisher] that publishes a non-terminating stream of messages from a device queue.
|
||||
/// It waits for new messages and publishes them in a loop. Useful when a client has finished receiving its stored
|
||||
/// messages and is now waiting for a live stream of new messages.
|
||||
public static FoundationDbMessagePublisher createInfinitePublisher(
|
||||
final KeySelector beginKeyInclusive,
|
||||
final KeySelector endKeyExclusive,
|
||||
final Database database,
|
||||
final MessageGuidCodec messageGuidCodec,
|
||||
final int maxMessagesPerScan,
|
||||
final byte[] messagesAvailableWatchKey) {
|
||||
|
||||
return new FoundationDbMessagePublisher(beginKeyInclusive,
|
||||
endKeyExclusive,
|
||||
database,
|
||||
messageGuidCodec,
|
||||
maxMessagesPerScan,
|
||||
messagesAvailableWatchKey,
|
||||
null);
|
||||
}
|
||||
|
||||
private synchronized void setState(final State newState, final Event event) {
|
||||
LOGGER.debug("Transitioned from state {} to state {} on event {}", state, newState, event);
|
||||
final State oldState = state;
|
||||
state = newState;
|
||||
stateChangeListener.accept(oldState, newState);
|
||||
}
|
||||
|
||||
/// Called when an event occurs. Transitions the current state to a new state if this is a defined transition.
|
||||
///
|
||||
/// @param event the {@link Event} that has occurred
|
||||
protected synchronized void transitionStateOnEvent(final Event event) {
|
||||
assert emitter != null;
|
||||
boolean knownTransition = true;
|
||||
switch (state) {
|
||||
case MESSAGES_AVAILABLE -> {
|
||||
switch (event) {
|
||||
case DEMAND_REQUESTED -> {
|
||||
setState(State.FETCHING_MESSAGES, event);
|
||||
emitMessages();
|
||||
}
|
||||
case INTERNAL_TRIGGER -> {
|
||||
if (emitter.requestedFromDownstream() > 0) {
|
||||
setState(State.FETCHING_MESSAGES, event);
|
||||
emitMessages();
|
||||
}
|
||||
}
|
||||
default -> knownTransition = false;
|
||||
}
|
||||
}
|
||||
case FETCHING_MESSAGES -> {
|
||||
switch (event) {
|
||||
case FETCHED_ALL_AVAILABLE_MESSAGES -> setState(State.QUEUE_EMPTY, event);
|
||||
case PUBLISHED_MESSAGES -> {
|
||||
setState(State.MESSAGES_AVAILABLE, event);
|
||||
transitionStateOnEvent(Event.INTERNAL_TRIGGER);
|
||||
}
|
||||
case FETCH_OR_PUBLISH_ERROR_OCCURRED -> setState(State.ERROR, event);
|
||||
default -> knownTransition = false;
|
||||
}
|
||||
}
|
||||
case QUEUE_EMPTY -> {
|
||||
if (terminateOnQueueEmpty) {
|
||||
switch (event) {
|
||||
case PUBLISHED_MESSAGES -> {
|
||||
setState(State.TERMINATED, event);
|
||||
emitter.complete();
|
||||
}
|
||||
case FETCHED_ALL_AVAILABLE_MESSAGES -> setState(State.ERROR, event);
|
||||
default -> knownTransition = false;
|
||||
}
|
||||
} else {
|
||||
switch (event) {
|
||||
case MESSAGE_AVAILABLE_WATCH_TRIGGERED -> setState(State.MESSAGE_AVAILABLE_SIGNAL_BUFFERED, event);
|
||||
case PUBLISHED_MESSAGES -> setState(State.AWAITING_NEW_MESSAGES, event);
|
||||
default -> knownTransition = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
case MESSAGE_AVAILABLE_SIGNAL_BUFFERED -> {
|
||||
switch (event) {
|
||||
case PUBLISHED_MESSAGES -> {
|
||||
setState(State.MESSAGES_AVAILABLE, event);
|
||||
transitionStateOnEvent(Event.INTERNAL_TRIGGER);
|
||||
}
|
||||
default -> knownTransition = false;
|
||||
}
|
||||
}
|
||||
case AWAITING_NEW_MESSAGES -> {
|
||||
switch (event) {
|
||||
case MESSAGE_AVAILABLE_WATCH_TRIGGERED -> {
|
||||
setState(State.MESSAGES_AVAILABLE, event);
|
||||
transitionStateOnEvent(Event.INTERNAL_TRIGGER);
|
||||
}
|
||||
default -> knownTransition = false;
|
||||
}
|
||||
}
|
||||
default -> knownTransition = false;
|
||||
}
|
||||
if (!knownTransition) {
|
||||
LOGGER.debug("Unhandled event {} on state {}", event, state);
|
||||
}
|
||||
}
|
||||
|
||||
/// Fetch messages using a range query limiting batch size to [#maxMessagesPerScan]. If the query returns fewer than
|
||||
/// [#maxMessagesPerScan], emit [Event#FETCHED_ALL_AVAILABLE_MESSAGES]. In the case of an infinite publisher, also set
|
||||
/// a watch for new messages. Additionally, the cursor is updated so that we begin fetching from the right key on
|
||||
/// subsequent scans
|
||||
///
|
||||
/// @return a future of a list of [MessageStreamEntry] with a max size of [#maxMessagesPerScan]
|
||||
private CompletableFuture<List<MessageStreamEntry.Envelope>> getMessagesBatch() {
|
||||
return database.runAsync(transaction -> getItemsInRange(transaction, messageGuidCodec, beginKeyCursor, endKeyExclusive, maxMessagesPerScan)
|
||||
.thenApply(lastKeyReadAndItems -> {
|
||||
// Set our beginning key to just past the last key read so that we're ready for our next fetch
|
||||
lastKeyReadAndItems.first().ifPresent(lastKeyRead -> beginKeyCursor = KeySelector.firstGreaterThan(lastKeyRead));
|
||||
|
||||
final List<MessageStreamEntry.Envelope> items = lastKeyReadAndItems.second();
|
||||
if (items.size() < maxMessagesPerScan) {
|
||||
transitionStateOnEvent(Event.FETCHED_ALL_AVAILABLE_MESSAGES);
|
||||
if (!terminateOnQueueEmpty) {
|
||||
setWatch(transaction);
|
||||
}
|
||||
}
|
||||
return items;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
/// Fetch messages in the range between `begin` and `end` limited to a batch size of `maxMessagesPerSccan`
|
||||
///
|
||||
/// @param transaction the FoundationDB transaction in which to perform the read query
|
||||
/// @param beginInclusive the range start key (inclusive)
|
||||
/// @param endExclusive the range end key (exclusive)
|
||||
/// @param maxMessagesPerScan maximum number of messages to return in the fetch query
|
||||
/// @return the last key read (if there were non-zero number of messages read) and the list of messages read
|
||||
private static CompletableFuture<Pair<Optional<byte[]>, List<MessageStreamEntry.Envelope>>> getItemsInRange(
|
||||
final Transaction transaction,
|
||||
final MessageGuidCodec messageGuidCodec,
|
||||
final KeySelector beginInclusive,
|
||||
final KeySelector endExclusive,
|
||||
final int maxMessagesPerScan) {
|
||||
return transaction.getRange(beginInclusive, endExclusive, maxMessagesPerScan, false, StreamingMode.EXACT).asList()
|
||||
.thenApply(keyValues -> {
|
||||
final Optional<byte[]> lastKeyRead = keyValues.isEmpty()
|
||||
? Optional.empty()
|
||||
: Optional.of(keyValues.getLast().getKey());
|
||||
final List<MessageStreamEntry.Envelope> messages = keyValues.stream()
|
||||
.map(keyValue -> {
|
||||
try {
|
||||
return new MessageStreamEntry.Envelope(MessageProtos.Envelope.parseFrom(keyValue.getValue())
|
||||
.toBuilder()
|
||||
.setServerGuidBinary(UUIDUtil.toByteString(messageGuidCodec.encodeMessageGuid(FoundationDbMessageStore.getVersionstamp(keyValue.getKey()))))
|
||||
.build());
|
||||
} catch (final InvalidProtocolBufferException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
})
|
||||
.toList();
|
||||
return new Pair<>(lastKeyRead, messages);
|
||||
});
|
||||
}
|
||||
|
||||
/// Fetch and publish messages. Messages are fetched in batches of [#maxMessagesPerScan] to avoid excessive memory
|
||||
/// consumption. After each fetch operation, [#beginKeyCursor] is updated to the next key we need to start reading
|
||||
/// from. If the fetch operation returns fewer items than the batch size, we infer that we have fetched all available
|
||||
/// messages and [Event#FETCHED_ALL_AVAILABLE_MESSAGES] is sent to the state machine. See [#getMessagesBatch()]
|
||||
/// for details. Additionally, after we successfully publish the batch of messages, {@link Event#PUBLISHED_MESSAGES}
|
||||
/// is emitted. If there's an error while fetching or publishing, [Event#FETCH_OR_PUBLISH_ERROR_OCCURRED] is emitted
|
||||
/// instead.
|
||||
private void emitMessages() {
|
||||
getMessagesBatch()
|
||||
.thenAccept(messageStreamEntries -> {
|
||||
messageStreamEntries.forEach(emitter::next);
|
||||
transitionStateOnEvent(Event.PUBLISHED_MESSAGES);
|
||||
})
|
||||
.exceptionally(t -> {
|
||||
transitionStateOnEvent(Event.FETCH_OR_PUBLISH_ERROR_OCCURRED);
|
||||
emitter.error(t);
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
/// Get the stream of messages.
|
||||
///
|
||||
/// @return [Flux] of messages
|
||||
public Flux<MessageStreamEntry.Envelope> getMessages() {
|
||||
return this.messagePublisher;
|
||||
}
|
||||
|
||||
private synchronized void setWatch(final Transaction transaction) {
|
||||
assert messagesAvailableWatchKey != null;
|
||||
// Set a watch that will be triggered when new messages arrive. When it is triggered, we attempt to fetch messages
|
||||
// again (if there is demand). When we run out of messages, this method will be called again, setting another watch,
|
||||
// and so on, thus achieving a "watch for new messages -> read -> publish" loop.
|
||||
watchFuture = transaction.watch(messagesAvailableWatchKey);
|
||||
watchFuture.thenRun(() -> transitionStateOnEvent(Event.MESSAGE_AVAILABLE_WATCH_TRIGGERED));
|
||||
}
|
||||
|
||||
private synchronized void onDispose() {
|
||||
// Unless the state machine is an already terminal state, directly set state to "terminated", since there's no point
|
||||
// in evaluating the state machine when there's no live subscription.
|
||||
if (state != State.TERMINATED && state != State.ERROR) {
|
||||
setState(State.TERMINATED, Event.INTERNAL_TRIGGER);
|
||||
}
|
||||
cancelWatch();
|
||||
}
|
||||
|
||||
/// Cancel the watch (if any). Although inactive watches are automatically timed-out, we explicitly cancel when the
|
||||
/// subscription is disposed to clean up associated resources and to avoid having too many watches open at once.
|
||||
private synchronized void cancelWatch() {
|
||||
if (watchFuture != null) {
|
||||
watchFuture.cancel(true);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+45
-14
@@ -22,6 +22,8 @@ import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.MessageStream;
|
||||
import org.whispersystems.textsecuregcm.util.Conversions;
|
||||
|
||||
/// An implementation of a message store backed by FoundationDB.
|
||||
@@ -38,6 +40,7 @@ import org.whispersystems.textsecuregcm.util.Conversions;
|
||||
public class FoundationDbMessageStore {
|
||||
|
||||
private final Database[] databases;
|
||||
private final VersionstampUUIDCipher versionstampUUIDCipher;
|
||||
private final Executor executor;
|
||||
private final Clock clock;
|
||||
|
||||
@@ -58,8 +61,13 @@ public class FoundationDbMessageStore {
|
||||
public record InsertResult(Optional<Versionstamp> versionstamp, boolean present) {
|
||||
}
|
||||
|
||||
public FoundationDbMessageStore(final Database[] databases, final Executor executor, final Clock clock) {
|
||||
public FoundationDbMessageStore(final Database[] databases,
|
||||
final VersionstampUUIDCipher versionstampUUIDCipher,
|
||||
final Executor executor,
|
||||
final Clock clock) {
|
||||
|
||||
this.databases = databases;
|
||||
this.versionstampUUIDCipher = versionstampUUIDCipher;
|
||||
this.executor = executor;
|
||||
this.clock = clock;
|
||||
}
|
||||
@@ -101,6 +109,14 @@ public class FoundationDbMessageStore {
|
||||
throw new IllegalArgumentException("One or more message bundles is empty");
|
||||
}
|
||||
|
||||
if (messagesByServiceIdentifier.values()
|
||||
.stream()
|
||||
.flatMap(messages -> messages.values().stream())
|
||||
.anyMatch(MessageProtos.Envelope::hasServerGuid)) {
|
||||
|
||||
throw new IllegalArgumentException("Messages must not have pre-set server GUIDs");
|
||||
}
|
||||
|
||||
final Map<Integer, List<Map.Entry<AciServiceIdentifier, Map<Byte, MessageProtos.Envelope>>>> messagesByShardId =
|
||||
messagesByServiceIdentifier.entrySet().stream()
|
||||
.collect(Collectors.groupingBy(entry -> hashAciToShardNumber(entry.getKey())));
|
||||
@@ -109,8 +125,6 @@ public class FoundationDbMessageStore {
|
||||
new ArrayList<>();
|
||||
|
||||
messagesByShardId.forEach((shardId, messagesForShard) -> {
|
||||
final Database shard = databases[shardId];
|
||||
|
||||
int start = 0, current = 0;
|
||||
int estimatedTransactionSize = 0;
|
||||
|
||||
@@ -121,7 +135,7 @@ public class FoundationDbMessageStore {
|
||||
.sum();
|
||||
|
||||
if (estimatedTransactionSize > MAX_MESSAGE_CHUNK_SIZE) {
|
||||
chunkFutures.add(insertChunk(shard, messagesForShard.subList(start, current)));
|
||||
chunkFutures.add(insertChunk(shardId, messagesForShard.subList(start, current)));
|
||||
|
||||
start = current;
|
||||
estimatedTransactionSize = 0;
|
||||
@@ -131,7 +145,7 @@ public class FoundationDbMessageStore {
|
||||
}
|
||||
|
||||
assert start < messagesForShard.size();
|
||||
chunkFutures.add(insertChunk(shard, messagesForShard.subList(start, messagesForShard.size())));
|
||||
chunkFutures.add(insertChunk(shardId, messagesForShard.subList(start, messagesForShard.size())));
|
||||
});
|
||||
|
||||
return CompletableFuture.allOf(chunkFutures.toArray(CompletableFuture[]::new))
|
||||
@@ -144,7 +158,7 @@ public class FoundationDbMessageStore {
|
||||
}
|
||||
|
||||
private CompletableFuture<Map<AciServiceIdentifier, Map<Byte, InsertResult>>> insertChunk(
|
||||
final Database database,
|
||||
final int shardId,
|
||||
final List<Map.Entry<AciServiceIdentifier, Map<Byte, MessageProtos.Envelope>>> messagesByAccountIdentifier) {
|
||||
|
||||
final Map<AciServiceIdentifier, CompletableFuture<Map<Byte, Boolean>>> insertFuturesByAci = new HashMap<>();
|
||||
@@ -156,7 +170,7 @@ public class FoundationDbMessageStore {
|
||||
.map(MessageProtos.Envelope::getEphemeral)
|
||||
.orElseThrow(() -> new IllegalStateException("One or more bundles is empty"));
|
||||
|
||||
return database.runAsync(transaction -> {
|
||||
return databases[shardId].runAsync(transaction -> {
|
||||
messagesByAccountIdentifier.forEach(entry ->
|
||||
insertFuturesByAci.put(entry.getKey(), insert(entry.getKey(), entry.getValue(), transaction)));
|
||||
|
||||
@@ -169,7 +183,7 @@ public class FoundationDbMessageStore {
|
||||
.anyMatch(isPresent -> isPresent);
|
||||
if (anyClientPresent || !ephemeral) {
|
||||
return transaction.getVersionstamp()
|
||||
.thenApply(versionstampBytes -> Optional.of(Versionstamp.complete(versionstampBytes)));
|
||||
.thenApply(versionstampBytes -> Optional.of(Versionstamp.complete(versionstampBytes, shardId)));
|
||||
}
|
||||
return CompletableFuture.completedFuture(Optional.<Versionstamp>empty());
|
||||
});
|
||||
@@ -220,7 +234,7 @@ public class FoundationDbMessageStore {
|
||||
if (isPresent || !message.getEphemeral()) {
|
||||
transaction.mutate(MutationType.SET_VERSIONSTAMPED_KEY,
|
||||
getDeviceQueueSubspace(aci, deviceId)
|
||||
.packWithVersionstamp(Tuple.from(Versionstamp.incomplete())), message.toByteArray());
|
||||
.packWithVersionstamp(Tuple.from(Versionstamp.incomplete(hashAciToShardNumber(aci)))), message.toByteArray());
|
||||
}
|
||||
|
||||
return isPresent;
|
||||
@@ -239,13 +253,30 @@ public class FoundationDbMessageStore {
|
||||
|
||||
if (anyClientPresent) {
|
||||
transaction.mutate(MutationType.SET_VERSIONSTAMPED_VALUE, getMessagesAvailableWatchKey(aci),
|
||||
Tuple.from(Versionstamp.incomplete()).packWithVersionstamp());
|
||||
Tuple.from(Versionstamp.incomplete(hashAciToShardNumber(aci))).packWithVersionstamp());
|
||||
}
|
||||
|
||||
return presenceByDeviceId;
|
||||
}, executor);
|
||||
}
|
||||
|
||||
public MessageStream getMessages(final AciServiceIdentifier aci, final Device destinationDevice) {
|
||||
return getMessages(aci, destinationDevice, FoundationDbMessageStream.DEFAULT_MAX_MESSAGES_PER_SCAN);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
MessageStream getMessages(final AciServiceIdentifier aci, final Device destinationDevice, final int maxMessagesPerScan) {
|
||||
return new FoundationDbMessageStream(getDeviceQueueSubspace(aci, destinationDevice.getId()),
|
||||
getMessagesAvailableWatchKey(aci),
|
||||
getShardForAci(aci),
|
||||
new MessageGuidCodec(aci.uuid(), destinationDevice.getId(), versionstampUUIDCipher),
|
||||
maxMessagesPerScan);
|
||||
}
|
||||
|
||||
static Versionstamp getVersionstamp(final byte[] messageKey) {
|
||||
return Tuple.fromBytes(messageKey).getVersionstamp(4);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
Database getShardForAci(final AciServiceIdentifier aci) {
|
||||
return databases[hashAciToShardNumber(aci)];
|
||||
@@ -258,20 +289,20 @@ public class FoundationDbMessageStore {
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
Subspace getDeviceQueueSubspace(final AciServiceIdentifier aci, final byte deviceId) {
|
||||
static Subspace getDeviceQueueSubspace(final AciServiceIdentifier aci, final byte deviceId) {
|
||||
return getDeviceSubspace(aci, deviceId).get("Q");
|
||||
}
|
||||
|
||||
private Subspace getDeviceSubspace(final AciServiceIdentifier aci, final byte deviceId) {
|
||||
private static Subspace getDeviceSubspace(final AciServiceIdentifier aci, final byte deviceId) {
|
||||
return getAccountSubspace(aci).get(deviceId);
|
||||
}
|
||||
|
||||
private Subspace getAccountSubspace(final AciServiceIdentifier aci) {
|
||||
private static Subspace getAccountSubspace(final AciServiceIdentifier aci) {
|
||||
return MESSAGES_SUBSPACE.get(aci.uuid());
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
byte[] getMessagesAvailableWatchKey(final AciServiceIdentifier aci) {
|
||||
static byte[] getMessagesAvailableWatchKey(final AciServiceIdentifier aci) {
|
||||
return getAccountSubspace(aci).pack("l");
|
||||
}
|
||||
|
||||
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
package org.whispersystems.textsecuregcm.storage.foundationdb;
|
||||
|
||||
import com.apple.foundationdb.Database;
|
||||
import com.apple.foundationdb.KeySelector;
|
||||
import com.apple.foundationdb.StreamingMode;
|
||||
import com.apple.foundationdb.subspace.Subspace;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Flow;
|
||||
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.storage.MessageStream;
|
||||
import org.whispersystems.textsecuregcm.storage.MessageStreamEntry;
|
||||
import reactor.adapter.JdkFlowAdapter;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
/// A [MessageStream] implementation that fetches messages from FoundationDB
|
||||
public class FoundationDbMessageStream implements MessageStream {
|
||||
|
||||
private final Subspace deviceQueueSubspace;
|
||||
private final byte[] messagesAvailableWatchKey;
|
||||
private final Database database;
|
||||
private final MessageGuidCodec messageGuidCodec;
|
||||
/// The maximum number of messages we will fetch per range query operation to avoid excessive memory consumption
|
||||
private final int maxMessagesPerScan;
|
||||
private final Flow.Publisher<MessageStreamEntry> messageStreamPublisher;
|
||||
|
||||
static final int DEFAULT_MAX_MESSAGES_PER_SCAN = 1024;
|
||||
|
||||
FoundationDbMessageStream(final Subspace deviceQueueSubspace,
|
||||
final byte[] messagesAvailableWatchKey,
|
||||
final Database database,
|
||||
final MessageGuidCodec messageGuidCodec,
|
||||
final int maxMessagesPerScan) {
|
||||
|
||||
this.deviceQueueSubspace = deviceQueueSubspace;
|
||||
this.messagesAvailableWatchKey = messagesAvailableWatchKey;
|
||||
this.database = database;
|
||||
this.messageGuidCodec = messageGuidCodec;
|
||||
this.maxMessagesPerScan = maxMessagesPerScan;
|
||||
this.messageStreamPublisher = JdkFlowAdapter.publisherToFlowPublisher(createMessagePublisher());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Flow.Publisher<MessageStreamEntry> getMessages() {
|
||||
return this.messageStreamPublisher;
|
||||
}
|
||||
|
||||
/// Create a message publisher
|
||||
///
|
||||
/// @return a Flux of {@link MessageStreamEntry} fetched from FoundationDB
|
||||
/// @implNote The message publisher is stitched together by concatenating:
|
||||
/// 1. **A finite message publisher**: On initial request, we record the current end-of-queue key in the device mailbox.
|
||||
/// Then, we fetch all messages in order until the recorded key and finally complete the stream
|
||||
/// 2. **A queue-empty signal** is emitted
|
||||
/// 3. **An infinite message publisher**: We start reading from where the finite publisher left off. When all messages
|
||||
/// are read, we wait for new messages, publish them, then wait again in a loop forever (until the flux is canceled
|
||||
/// explicitly or due to an error). This is accomplished by setting a FoundationDB [watch](https://github.com/apple/foundationdb/wiki/An-Overview-how-Watches-Work)
|
||||
/// on [#messagesAvailableWatchKey] which is updated when a new message is available.
|
||||
/// See [FoundationDbMessageStore] for more details on the message insert process.
|
||||
private Flux<MessageStreamEntry> createMessagePublisher() {
|
||||
return Mono.fromFuture(this::getEndOfQueueKeyExclusive)
|
||||
.flatMapMany(maybeEndOfQueueKeyExclusive -> {
|
||||
final Flux<MessageStreamEntry.Envelope> finitePublisher = maybeEndOfQueueKeyExclusive
|
||||
.map(endOfQueueKeyExclusive -> FoundationDbMessagePublisher.createFinitePublisher(
|
||||
KeySelector.firstGreaterOrEqual(deviceQueueSubspace.range().begin),
|
||||
endOfQueueKeyExclusive, database, messageGuidCodec, maxMessagesPerScan).getMessages())
|
||||
.orElseGet(Flux::empty);
|
||||
final KeySelector infinitePublisherBeginKey = maybeEndOfQueueKeyExclusive.orElseGet(
|
||||
() -> KeySelector.firstGreaterOrEqual(deviceQueueSubspace.range().begin));
|
||||
final Flux<MessageStreamEntry.Envelope> infinitePublisher = FoundationDbMessagePublisher.createInfinitePublisher(
|
||||
infinitePublisherBeginKey, KeySelector.firstGreaterThan(deviceQueueSubspace.range().end),
|
||||
database, messageGuidCodec, maxMessagesPerScan, messagesAvailableWatchKey).getMessages();
|
||||
return Flux.concat(
|
||||
finitePublisher,
|
||||
Mono.just(new MessageStreamEntry.QueueEmpty()),
|
||||
infinitePublisher
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/// Gets a [KeySelector] for the first key greater than the current greatest key in the device queue. This allows
|
||||
/// us to query keys up to and including the greatest key, and sets us up to begin reading from the next key in
|
||||
/// a subsequent scan.
|
||||
/// @return a [KeySelector] for the first key greater than the current greatest key in the device queue.
|
||||
private CompletableFuture<Optional<KeySelector>> getEndOfQueueKeyExclusive() {
|
||||
return database.runAsync(
|
||||
transaction -> transaction.getRange(deviceQueueSubspace.range(), 1, true, StreamingMode.EXACT).asList()
|
||||
.thenApply(items -> {
|
||||
if (items.isEmpty()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
assert items.size() == 1;
|
||||
return Optional.of(KeySelector.firstGreaterThan(items.getFirst().getKey()));
|
||||
}));
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Void> acknowledgeMessage(final MessageProtos.Envelope message) {
|
||||
throw new UnsupportedOperationException("Not implemented");
|
||||
}
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage.foundationdb;
|
||||
|
||||
import com.apple.foundationdb.tuple.Versionstamp;
|
||||
import java.util.UUID;
|
||||
|
||||
class MessageGuidCodec {
|
||||
|
||||
private final UUID accountIdentifier;
|
||||
private final byte deviceId;
|
||||
private final VersionstampUUIDCipher versionstampUUIDCipher;
|
||||
|
||||
MessageGuidCodec(final UUID accountIdentifier,
|
||||
final byte deviceId,
|
||||
final VersionstampUUIDCipher versionstampUUIDCipher) {
|
||||
|
||||
this.accountIdentifier = accountIdentifier;
|
||||
this.deviceId = deviceId;
|
||||
this.versionstampUUIDCipher = versionstampUUIDCipher;
|
||||
}
|
||||
|
||||
public UUID encodeMessageGuid(final Versionstamp versionstamp) {
|
||||
return versionstampUUIDCipher.encryptVersionstamp(versionstamp, accountIdentifier, deviceId);
|
||||
}
|
||||
|
||||
public Versionstamp decodeMessageGuid(final UUID messageGuid) {
|
||||
return versionstampUUIDCipher.decryptVersionstamp(messageGuid, accountIdentifier, deviceId);
|
||||
}
|
||||
}
|
||||
+330
@@ -0,0 +1,330 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage.foundationdb;
|
||||
|
||||
import com.apple.foundationdb.tuple.Versionstamp;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.security.InvalidAlgorithmParameterException;
|
||||
import java.security.InvalidKeyException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.UUID;
|
||||
import javax.crypto.BadPaddingException;
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.IllegalBlockSizeException;
|
||||
import javax.crypto.NoSuchPaddingException;
|
||||
import javax.crypto.SecretKey;
|
||||
import javax.crypto.ShortBufferException;
|
||||
import javax.crypto.spec.IvParameterSpec;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
|
||||
/// A versionstamp/UUID cipher encrypts and encodes FoundationDB [Versionstamp] instances as version 8 UUIDs and decodes
|
||||
/// and decrypts UUIDs as `Versionstamps`.
|
||||
///
|
||||
/// @implNote This cipher uses the NIST FF1 format-preserving encryption algorithm to encrypt `Versionstamps`. It uses
|
||||
/// a global, static AES key (although message GUIDs encode a key ID to facilitate key rotation should the need arise)
|
||||
/// and uses the receiving device's ID and account identifier as a "tweak."
|
||||
///
|
||||
/// The layout of returned UUIDs is as follows:
|
||||
///
|
||||
/// ```
|
||||
/// 0 1 2 3
|
||||
/// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
|
||||
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|
||||
/// | versionstamp_a |
|
||||
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|
||||
/// | versionstamp_a | v_U | v_F | reserved |
|
||||
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|
||||
/// |var| key_id | reserved | versionstamp_b |
|
||||
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|
||||
/// | versionstamp_b |
|
||||
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|
||||
/// ```
|
||||
///
|
||||
/// Where:
|
||||
///
|
||||
/// - `versionstamp_a` is the first 48 bits of a versionstamp encrypted with NIST FF1
|
||||
/// - `versionstamp_b` is the latter 48 bits of a versionstamp encrypted with NIST FF1
|
||||
/// - `key_id` is a 6-bit identifier for the key used to encrypt the versionstamp (initially 0b000001)
|
||||
/// - `v_F` is 4-bit version of our application-specific v8 UUID format (initially 0b0001)
|
||||
/// - `v_U` is the 4-bit version for a v8 UUID (i.e. 0b1000)
|
||||
/// - `var` is the 2-bit variant for a v8 UUID (i.e. 0b10)
|
||||
/// - `reserved` bits have no semantic meaning in the current version of the format and are reserved for future use
|
||||
///
|
||||
/// @see <a href="https://csrc.nist.gov/pubs/sp/800/38/g/r1/2pd">Recommendation for Block Cipher Modes of Operation: Methods for Format-Preserving Encryption</a>
|
||||
/// @see <a href="https://apple.github.io/foundationdb/data-modeling.html#versionstamps">FoundationDB - Data Modeling - Versionstamps</a>
|
||||
/// @see <a href="https://www.rfc-editor.org/rfc/rfc9562.html#name-uuid-version-8">RFC 9562 Universally Unique IDentifiers (UUIDs), Section 5.8: UUID Version 8</a>
|
||||
public class VersionstampUUIDCipher {
|
||||
|
||||
private final byte keyId;
|
||||
private final SecretKey key;
|
||||
|
||||
@VisibleForTesting
|
||||
static final byte FORMAT_VERSION = 0x01;
|
||||
|
||||
private static final int VERSIONSTAMP_LENGTH = 12; // bytes
|
||||
private static final int TWEAK_LENGTH = 17; // bytes
|
||||
private static final byte ROUNDS = 10; // from FF1 specification
|
||||
|
||||
private static final IvParameterSpec IV_PARAMETERS = new IvParameterSpec(new byte[] {
|
||||
0x01, // static value from FF1 specification
|
||||
0x02, // static value from FF1 specification
|
||||
0x01, // static value from FF1 specification
|
||||
0x00, 0x00, 0x02, // radix
|
||||
ROUNDS,
|
||||
(VERSIONSTAMP_LENGTH * 8) / 2,
|
||||
0x00, 0x00, 0x00, VERSIONSTAMP_LENGTH * 8, // for radix = 2, plaintext/ciphertext length in bits
|
||||
0x00, 0x00, 0x00, TWEAK_LENGTH, // tweak length in bytes (not bits)
|
||||
});
|
||||
|
||||
private static final long LEAST_SIGNIFICANT_SIX_BYTES_MASK = 0x0000_ffff_ffff_ffffL;
|
||||
private static final byte FORMAT_VERSION_MASK = 0x0f;
|
||||
private static final byte KEY_ID_MASK = 0x3f;
|
||||
|
||||
static {
|
||||
//noinspection ConstantValue
|
||||
assert (FORMAT_VERSION & FORMAT_VERSION_MASK) == FORMAT_VERSION;
|
||||
}
|
||||
|
||||
/// Constructs a new cipher with the given AES key.
|
||||
///
|
||||
/// @param keyId an identifier for the given AES encryption key; must be between 0 and 63, inclusive
|
||||
/// @param keyBytes the raw bytes of an AES encryption key
|
||||
///
|
||||
/// @throws IllegalArgumentException if the given `keyBytes` could not be used as an AES key
|
||||
public VersionstampUUIDCipher(final int keyId, final byte[] keyBytes) {
|
||||
if (keyId != (keyId & KEY_ID_MASK)) {
|
||||
throw new IllegalArgumentException("Key ID must be between 0 and 63, inclusive");
|
||||
}
|
||||
|
||||
this.keyId = (byte) (keyId & KEY_ID_MASK);
|
||||
this.key = new SecretKeySpec(keyBytes, "AES");
|
||||
|
||||
// Fail fast on invalid parameters
|
||||
try {
|
||||
getCipher().init(Cipher.ENCRYPT_MODE, key, IV_PARAMETERS);
|
||||
} catch (final InvalidAlgorithmParameterException e) {
|
||||
throw new AssertionError("Known, static IV invalid", e);
|
||||
} catch (final InvalidKeyException e) {
|
||||
throw new IllegalArgumentException("Key bytes could not be used as an AES key", e);
|
||||
}
|
||||
}
|
||||
|
||||
/// Encrypts a `Versionstamp` and encodes it as version 8 UUID the given account identifier.
|
||||
///
|
||||
/// @implNote the account identifier is used as a cryptographic "tweak" as described in the FF1 specification
|
||||
///
|
||||
/// @param versionstamp the versionstamp to encrypt
|
||||
/// @param accountIdentifier the account identifier for which to encrypt the versionstamp
|
||||
/// @param deviceId the ID of the device within the given account for which to encrypt the versionstamp
|
||||
///
|
||||
/// @return a version 8 UUID that encodes the encrypted versionstamp
|
||||
///
|
||||
/// @see #decryptVersionstamp(UUID, UUID, byte)
|
||||
public UUID encryptVersionstamp(final Versionstamp versionstamp, final UUID accountIdentifier, final byte deviceId) {
|
||||
final Cipher cipher = getCipher();
|
||||
final byte[] buffer = new byte[16];
|
||||
|
||||
long a, b;
|
||||
{
|
||||
final long[] longs = byteArrayToLongs(versionstamp.getBytes());
|
||||
|
||||
a = longs[0];
|
||||
b = longs[1];
|
||||
}
|
||||
|
||||
for (byte round = 0; round < ROUNDS; round++) {
|
||||
final long c = (a + doRound(cipher, accountIdentifier, deviceId, round, b, buffer)) & LEAST_SIGNIFICANT_SIX_BYTES_MASK;
|
||||
|
||||
a = b;
|
||||
b = c;
|
||||
}
|
||||
|
||||
final long uuidVersionAndFormatVersion = (0x80L | (FORMAT_VERSION & FORMAT_VERSION_MASK)) << 8;
|
||||
final long uuidVariantAndKeyId = (0x80L | (keyId)) << 56;
|
||||
|
||||
return new UUID(a << 16 | uuidVersionAndFormatVersion, b | uuidVariantAndKeyId);
|
||||
}
|
||||
|
||||
/// Decrypts a versionstamp encoded as a version 8 UUID for the given account identifier and device ID.
|
||||
///
|
||||
/// @implNote the account identifier and device ID are used as a cryptographic "tweak" as described in the FF1
|
||||
/// specification
|
||||
///
|
||||
/// @param encryptedVersionstamp the encrypted versionstamp to decrypt
|
||||
/// @param accountIdentifier the account identifier for which to decrypt the versionstamp
|
||||
/// @param deviceId the ID of the device within the account for which to decrypt the versionstamp
|
||||
///
|
||||
/// @return the versionstamp from the given ciphertext and for the given account identifier and device ID
|
||||
public Versionstamp decryptVersionstamp(final UUID encryptedVersionstamp, final UUID accountIdentifier, final byte deviceId) {
|
||||
if (encryptedVersionstamp.version() != 8) {
|
||||
throw new IllegalArgumentException("Unexpected UUID version");
|
||||
}
|
||||
|
||||
if (getFormatVersion(encryptedVersionstamp) != FORMAT_VERSION) {
|
||||
throw new IllegalArgumentException("Unexpected format version");
|
||||
}
|
||||
|
||||
if (getKeyId(encryptedVersionstamp) != keyId) {
|
||||
throw new IllegalArgumentException("Unexpected key ID");
|
||||
}
|
||||
|
||||
final Cipher cipher = getCipher();
|
||||
final byte[] buffer = new byte[16];
|
||||
|
||||
long a = encryptedVersionstamp.getMostSignificantBits() >>> 16;
|
||||
long b = encryptedVersionstamp.getLeastSignificantBits() & LEAST_SIGNIFICANT_SIX_BYTES_MASK;
|
||||
|
||||
for (byte round = ROUNDS - 1; round >= 0; round--) {
|
||||
final long c = b;
|
||||
b = a;
|
||||
|
||||
a = (c - doRound(cipher, accountIdentifier, deviceId, round, b, buffer)) & LEAST_SIGNIFICANT_SIX_BYTES_MASK;
|
||||
}
|
||||
|
||||
return Versionstamp.fromBytes(longsToByteArray(a, b));
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static byte getFormatVersion(final UUID encryptedVersionstamp) {
|
||||
if (encryptedVersionstamp.version() != 8) {
|
||||
throw new IllegalArgumentException("Unexpected UUID version");
|
||||
}
|
||||
|
||||
return (byte) ((encryptedVersionstamp.getMostSignificantBits() & 0x0000_0000_0000_0f00L) >>> 8);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static byte getKeyId(final UUID encryptedVersionstamp) {
|
||||
if (encryptedVersionstamp.version() != 8) {
|
||||
throw new IllegalArgumentException("Unexpected UUID version");
|
||||
}
|
||||
|
||||
return (byte) ((encryptedVersionstamp.getLeastSignificantBits() & 0x3f00_0000_0000_0000L) >>> 56);
|
||||
}
|
||||
|
||||
private long doRound(final Cipher cipher,
|
||||
final UUID accountIdentifier,
|
||||
final byte deviceId,
|
||||
final byte round,
|
||||
final long b,
|
||||
final byte[] bufferArray) {
|
||||
|
||||
try {
|
||||
cipher.init(Cipher.ENCRYPT_MODE, key, IV_PARAMETERS);
|
||||
} catch (final InvalidKeyException e) {
|
||||
throw new AssertionError("Previously-valid key now invalid", e);
|
||||
} catch (final InvalidAlgorithmParameterException e) {
|
||||
throw new AssertionError("Previously-valid IV now invalid", e);
|
||||
}
|
||||
|
||||
assert (b & ~LEAST_SIGNIFICANT_SIX_BYTES_MASK) == 0;
|
||||
|
||||
final ByteBuffer byteBuffer = ByteBuffer.wrap(bufferArray);
|
||||
|
||||
// Write the first part of cryptographic "tweak" into the buffer. We have one more byte (the device ID) that will
|
||||
// "spill" over into the next block, but that's okay! That extra byte falls into the "padding zone" of the next
|
||||
// block, and doesn't increase the overall block count per round.
|
||||
byteBuffer
|
||||
.putLong(0, accountIdentifier.getMostSignificantBits())
|
||||
.putLong(8, accountIdentifier.getLeastSignificantBits());
|
||||
|
||||
try {
|
||||
// We can overwrite the input buffer here to avoid allocating an additional 16-byte buffer that we'd just
|
||||
// discard immediately
|
||||
cipher.update(bufferArray, 0, bufferArray.length, bufferArray);
|
||||
|
||||
// We want to wind up with the device ID (the last byte of the "tweak"), followed by 8 bytes of zeroes, followed
|
||||
// by a one-byte round counter, finally followed by the lowest 6 bytes of `b`. The highest two bytes of `b` are
|
||||
// already 0 (as asserted above). We write `b` first so we can overwrite one of its high bytes with the round
|
||||
// counter. Note that we can overwrite the AES-CBC output block that's currently in the buffer; it's just an
|
||||
// intermediate value that we don't actually need to return (even though it's used internally by AES-CBC).
|
||||
byteBuffer
|
||||
.putLong(0, 0L)
|
||||
.put(0, deviceId)
|
||||
.putLong(8, b)
|
||||
.put(9, round);
|
||||
|
||||
// Again, overwrite the input buffer to avoid an extra buffer allocation…
|
||||
cipher.update(bufferArray, 0, bufferArray.length, bufferArray);
|
||||
|
||||
// …and then overwrite the buffer once more with the cipher's finished output, which is the only AES-CBC output we
|
||||
// actually use directly.
|
||||
final int bytesWritten = cipher.doFinal(bufferArray, 0);
|
||||
assert bytesWritten == 16;
|
||||
|
||||
return byteBuffer.getLong(0) & LEAST_SIGNIFICANT_SIX_BYTES_MASK;
|
||||
} catch (final IllegalBlockSizeException | BadPaddingException e) {
|
||||
throw new AssertionError("Every implementation of the Java platform is required to support AES/CBC/PKCS5Padding", e);
|
||||
} catch (final ShortBufferException e) {
|
||||
throw new AssertionError("Buffer with known length of 16 too short", e);
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a `Cipher` instance suitable for use in the core NIST/FF1 loop.
|
||||
///
|
||||
/// @return a `Cipher` instance suitable for use in the core NIST/FF1 loop
|
||||
private static Cipher getCipher() {
|
||||
try {
|
||||
return Cipher.getInstance("AES/CBC/PKCS5Padding");
|
||||
} catch (final NoSuchAlgorithmException | NoSuchPaddingException e) {
|
||||
throw new AssertionError("Every implementation of the Java platform is required to support AES/CBC/PKCS5Padding", e);
|
||||
}
|
||||
}
|
||||
|
||||
/// Encode a 96-bit value, supplied as a `byte[12]`, as a pair of right-aligned `long`s. The first `long` contains the
|
||||
/// first six bytes of the input and the second `long` contains the next six bytes, both interpreted in big-endian
|
||||
/// order. That is, given the `byte` array `{ 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc}`,
|
||||
/// this function will return the `long` array `{ 0x0000_1122_3344_5566, 0x0000_7788_99aa_bbcc }`.
|
||||
///
|
||||
/// @param bytes the bytes to encode as a pair of `long`s
|
||||
///
|
||||
/// @return a pair of `long` instances that encode the original value
|
||||
///
|
||||
/// @see #longsToByteArray(long, long)
|
||||
@VisibleForTesting
|
||||
static long[] byteArrayToLongs(final byte[] bytes) {
|
||||
assert bytes.length == VERSIONSTAMP_LENGTH;
|
||||
|
||||
final ByteBuffer buffer = ByteBuffer.wrap(bytes);
|
||||
|
||||
return new long[] {
|
||||
buffer.getLong(0) >>> 16,
|
||||
buffer.getLong(4) & LEAST_SIGNIFICANT_SIX_BYTES_MASK
|
||||
};
|
||||
}
|
||||
|
||||
/// Packs the least-significant 48 bits of the given `long`s into a single 96-bit array. The least significant 48 bits
|
||||
/// of the first `long` become the first 48 bits of the returned array, and the least significant bits of the second
|
||||
/// `long` become the second 48 bits of the returned array, both encoded in big-endian order.
|
||||
///
|
||||
/// @param mostSignificantBits a `long` carrying the most significant 48 bits of the combined value
|
||||
/// @param leastSignificantBits a `long` carrying the least significant 48 bits of the combined value
|
||||
///
|
||||
/// @return a byte array containing the combined 96-bit value from the two given `long`s
|
||||
///
|
||||
/// @see #byteArrayToLongs(byte[])
|
||||
@VisibleForTesting
|
||||
static byte[] longsToByteArray(final long mostSignificantBits, final long leastSignificantBits) {
|
||||
final byte[] versionstamp = new byte[VERSIONSTAMP_LENGTH];
|
||||
|
||||
versionstamp[0] = (byte) (mostSignificantBits >> 40 & 0xff);
|
||||
versionstamp[1] = (byte) (mostSignificantBits >> 32 & 0xff);
|
||||
versionstamp[2] = (byte) (mostSignificantBits >> 24 & 0xff);
|
||||
versionstamp[3] = (byte) (mostSignificantBits >> 16 & 0xff);
|
||||
versionstamp[4] = (byte) (mostSignificantBits >> 8 & 0xff);
|
||||
versionstamp[5] = (byte) (mostSignificantBits & 0xff);
|
||||
|
||||
versionstamp[6] = (byte) (leastSignificantBits >> 40 & 0xff);
|
||||
versionstamp[7] = (byte) (leastSignificantBits >> 32 & 0xff);
|
||||
versionstamp[8] = (byte) (leastSignificantBits >> 24 & 0xff);
|
||||
versionstamp[9] = (byte) (leastSignificantBits >> 16 & 0xff);
|
||||
versionstamp[10] = (byte) (leastSignificantBits >> 8 & 0xff);
|
||||
versionstamp[11] = (byte) (leastSignificantBits & 0xff);
|
||||
|
||||
return versionstamp;
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -184,7 +184,7 @@ public class AppleAppStoreClient {
|
||||
private static boolean shouldRetry(Throwable e) {
|
||||
return e instanceof APIException apiException && switch (apiException.getApiError()) {
|
||||
case ORIGINAL_TRANSACTION_ID_NOT_FOUND_RETRYABLE, GENERAL_INTERNAL_RETRYABLE, APP_NOT_FOUND_RETRYABLE -> true;
|
||||
default -> false;
|
||||
case null, default -> false;
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -55,6 +55,10 @@ public final class HeaderUtils {
|
||||
return "Basic " + Base64.getEncoder().encodeToString((username + ":" + password).getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
public static String bearerAuthHeader(final String token) {
|
||||
return "Bearer " + token;
|
||||
}
|
||||
|
||||
@Nonnull
|
||||
public static String getTimestampHeader() {
|
||||
return TIMESTAMP_HEADER + ":" + System.currentTimeMillis();
|
||||
|
||||
+52
-4
@@ -10,17 +10,35 @@ import io.dropwizard.core.cli.ServerCommand;
|
||||
import io.dropwizard.core.server.DefaultServerFactory;
|
||||
import io.dropwizard.core.setup.Environment;
|
||||
import io.dropwizard.jetty.HttpsConnectorFactory;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import net.sourceforge.argparse4j.inf.Namespace;
|
||||
import net.sourceforge.argparse4j.inf.Subparser;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagePersister;
|
||||
import org.whispersystems.textsecuregcm.util.logging.UncaughtExceptionHandler;
|
||||
import reactor.core.publisher.Hooks;
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
import reactor.core.scheduler.Schedulers;
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
public class MessagePersisterServiceCommand extends ServerCommand<WhisperServerConfiguration> {
|
||||
|
||||
private static final String WORKER_COUNT = "workers";
|
||||
@Nullable
|
||||
private ExecutorService persistQueueExecutorService;
|
||||
|
||||
@Nullable
|
||||
private Scheduler persistQueueScheduler;
|
||||
|
||||
private static final String MAX_CONCURRENCY = "maxConcurrency";
|
||||
private static final String SCAN_COUNT = "scanCount";
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(MessagePersisterServiceCommand.class);
|
||||
|
||||
public MessagePersisterServiceCommand() {
|
||||
super(new Application<>() {
|
||||
@@ -35,11 +53,20 @@ public class MessagePersisterServiceCommand extends ServerCommand<WhisperServerC
|
||||
@Override
|
||||
public void configure(final Subparser subparser) {
|
||||
super.configure(subparser);
|
||||
|
||||
// This is a deliberate misnomer for consistency with other service commands that expect a worker count
|
||||
subparser.addArgument("--workers")
|
||||
.type(Integer.class)
|
||||
.dest(WORKER_COUNT)
|
||||
.dest(MAX_CONCURRENCY)
|
||||
.required(true)
|
||||
.help("The number of worker threads");
|
||||
.help("The maximum number of concurrent Redis/DynamoDB operations");
|
||||
|
||||
subparser.addArgument("--scan-count")
|
||||
.type(Integer.class)
|
||||
.dest(SCAN_COUNT)
|
||||
.required(false)
|
||||
.setDefault(1024)
|
||||
.help("The COUNT argument for the Redis SCAN operation that finds message queues");
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -47,6 +74,7 @@ public class MessagePersisterServiceCommand extends ServerCommand<WhisperServerC
|
||||
throws Exception {
|
||||
|
||||
UncaughtExceptionHandler.register();
|
||||
Hooks.onErrorDropped(e -> logger.warn("Dropped message persistence error", e));
|
||||
|
||||
final CommandDependencies deps = CommandDependencies.build("message-persister-service", environment, configuration);
|
||||
MetricsUtil.configureRegistries(configuration, environment, deps.dynamicConfigurationManager());
|
||||
@@ -60,16 +88,36 @@ public class MessagePersisterServiceCommand extends ServerCommand<WhisperServerC
|
||||
});
|
||||
}
|
||||
|
||||
persistQueueExecutorService = Executors.newVirtualThreadPerTaskExecutor();
|
||||
persistQueueScheduler = Schedulers.fromExecutorService(persistQueueExecutorService, "persistQueue");
|
||||
|
||||
final MessagePersister messagePersister = new MessagePersister(deps.messagesCache(),
|
||||
deps.messagesManager(),
|
||||
deps.accountsManager(),
|
||||
deps.dynamicConfigurationManager(),
|
||||
persistQueueScheduler,
|
||||
Clock.systemUTC(),
|
||||
Duration.ofMinutes(configuration.getMessageCacheConfiguration().getPersistDelayMinutes()),
|
||||
namespace.getInt(WORKER_COUNT));
|
||||
namespace.getInt(MAX_CONCURRENCY),
|
||||
namespace.getInt(SCAN_COUNT));
|
||||
|
||||
environment.lifecycle().manage(messagePersister);
|
||||
|
||||
super.run(environment, namespace, configuration);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void cleanup() {
|
||||
super.cleanup();
|
||||
|
||||
Hooks.resetOnErrorDropped();
|
||||
|
||||
if (persistQueueScheduler != null) {
|
||||
persistQueueScheduler.dispose();
|
||||
}
|
||||
|
||||
if (persistQueueExecutorService != null) {
|
||||
persistQueueExecutorService.shutdown();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ package org.signal.chat.account;
|
||||
import "org/signal/chat/common.proto";
|
||||
import "org/signal/chat/errors.proto";
|
||||
import "org/signal/chat/require.proto";
|
||||
import "org/signal/chat/tag.proto";
|
||||
|
||||
// Provides methods for working with Signal accounts.
|
||||
service Accounts {
|
||||
@@ -115,7 +116,7 @@ message ReserveUsernameHashResponse {
|
||||
|
||||
// Indicates that, of all of the candidate hashes provided, none were
|
||||
// available. Callers may generate a new set of hashes and and retry.
|
||||
UsernameNotAvailable username_not_available = 2;
|
||||
UsernameNotAvailable username_not_available = 2 [(tag.reason) = "username_not_available"];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -146,11 +147,11 @@ message ConfirmUsernameHashResponse {
|
||||
ConfirmedUsernameHash confirmed_username_hash = 1;
|
||||
|
||||
// The provided hash was not reserved for the account.
|
||||
errors.FailedPrecondition reservation_not_found = 2;
|
||||
errors.FailedPrecondition reservation_not_found = 2 [(tag.reason) = "reservation_not_found"];
|
||||
|
||||
// The reservation has lapsed and the requested username has been claimed by
|
||||
// another caller.
|
||||
UsernameNotAvailable username_not_available = 3;
|
||||
UsernameNotAvailable username_not_available = 3 [(tag.reason) = "username_not_available"];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -177,7 +178,7 @@ message SetUsernameLinkResponse {
|
||||
bytes username_link_handle = 1;
|
||||
|
||||
// The authenticated account did not have a username set.
|
||||
errors.FailedPrecondition no_username_set = 2;
|
||||
errors.FailedPrecondition no_username_set = 2 [(tag.reason) = "no_username_set"];
|
||||
|
||||
}
|
||||
}
|
||||
@@ -244,7 +245,7 @@ message LookupUsernameHashResponse {
|
||||
common.ServiceIdentifier service_identifier = 1;
|
||||
|
||||
// No account was found for the provided username hash.
|
||||
errors.NotFound not_found = 2;
|
||||
errors.NotFound not_found = 2 [(tag.reason) = "not_found"];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -261,6 +262,6 @@ message LookupUsernameLinkResponse {
|
||||
|
||||
|
||||
// No username was found for the provided link handle.
|
||||
errors.NotFound not_found = 2;
|
||||
errors.NotFound not_found = 2 [(tag.reason) = "not_found"];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
syntax = "proto3";
|
||||
|
||||
option java_multiple_files = true;
|
||||
|
||||
package org.signal.chat.attachments;
|
||||
|
||||
import "org/signal/chat/common.proto";
|
||||
import "org/signal/chat/require.proto";
|
||||
import "org/signal/chat/errors.proto";
|
||||
import "org/signal/chat/tag.proto";
|
||||
|
||||
service Attachments {
|
||||
option (require.auth) = AUTH_ONLY_AUTHENTICATED;
|
||||
|
||||
// Retrieve an upload form that can be used to perform a resumable upload
|
||||
rpc GetUploadForm(GetUploadFormRequest) returns (GetUploadFormResponse) {}
|
||||
}
|
||||
|
||||
message GetUploadFormRequest {
|
||||
// The length of the attachment for the requested upload form. Uploads
|
||||
// performed with this form will be limited to the provided length.
|
||||
uint64 uploadLength = 1 [(require.range) = {min: 1}];
|
||||
}
|
||||
|
||||
message GetUploadFormResponse {
|
||||
oneof outcome {
|
||||
common.UploadForm upload_form = 1;
|
||||
|
||||
// The request size was larger than the maximum supported upload size. The
|
||||
// maximum upload size is subject to change and is governed by
|
||||
// `global.attachments.maxBytes`
|
||||
errors.FailedPrecondition exceeds_max_upload_length = 2 [(tag.reason) = "oversize_upload"];
|
||||
}
|
||||
}
|
||||
@@ -84,7 +84,7 @@ message RedeemReceiptRequest {
|
||||
}
|
||||
|
||||
message RedeemReceiptResponse {
|
||||
oneof outcome {
|
||||
oneof response {
|
||||
// The receipt was successfully redeemed
|
||||
google.protobuf.Empty success = 1;
|
||||
|
||||
@@ -217,7 +217,7 @@ message SetPublicKeyRequest {
|
||||
}
|
||||
|
||||
message SetPublicKeyResponse {
|
||||
oneof outcome {
|
||||
oneof response {
|
||||
// The public key was successfully set
|
||||
google.protobuf.Empty success = 1;
|
||||
|
||||
@@ -240,7 +240,7 @@ message GetCdnCredentialsResponse {
|
||||
message CdnCredentials {
|
||||
map<string, string> headers = 1;
|
||||
}
|
||||
oneof outcome {
|
||||
oneof response {
|
||||
// Headers to include with requests to the read from the backup CDN. Includes
|
||||
// time limited read-only credentials.
|
||||
CdnCredentials cdn_credentials = 1;
|
||||
@@ -266,7 +266,7 @@ message GetSvrBCredentialsResponse {
|
||||
string password = 2;
|
||||
}
|
||||
|
||||
oneof outcome {
|
||||
oneof response {
|
||||
SvrBCredentials svrb_credentials = 1;
|
||||
|
||||
// The provided backup auth credential presentation could not be
|
||||
@@ -295,7 +295,7 @@ message GetMessageBackupInfoResponse {
|
||||
string backup_name = 3;
|
||||
}
|
||||
|
||||
oneof outcome {
|
||||
oneof response {
|
||||
MessageBackupInfo backup_info = 1;
|
||||
|
||||
// The provided backup auth credential presentation could not be
|
||||
@@ -319,7 +319,7 @@ message GetMediaBackupInfoResponse {
|
||||
uint64 used_space = 3;
|
||||
}
|
||||
|
||||
oneof outcome {
|
||||
oneof response {
|
||||
MediaBackupInfo backup_info = 1;
|
||||
|
||||
// The provided backup auth credential presentation could not be
|
||||
@@ -334,7 +334,7 @@ message RefreshRequest {
|
||||
SignedPresentation signed_presentation = 1;
|
||||
}
|
||||
message RefreshResponse {
|
||||
oneof outcome {
|
||||
oneof response {
|
||||
// The backup was successfully refreshed
|
||||
google.protobuf.Empty success = 1;
|
||||
|
||||
@@ -349,9 +349,7 @@ message RefreshResponse {
|
||||
message GetUploadFormRequest {
|
||||
SignedPresentation signed_presentation = 1;
|
||||
|
||||
message MessagesUploadType {
|
||||
uint64 upload_length = 1;
|
||||
}
|
||||
message MessagesUploadType {}
|
||||
message MediaUploadType {}
|
||||
oneof upload_type {
|
||||
// Retrieve an upload form that can be used to perform a resumable upload of
|
||||
@@ -365,25 +363,14 @@ message GetUploadFormRequest {
|
||||
// Behaves identically to the account authenticated version at /attachments.
|
||||
MediaUploadType media = 3;
|
||||
}
|
||||
|
||||
// The length of the attachment for the requested upload form. Uploads
|
||||
// performed with this form will be limited to the provided length.
|
||||
uint64 uploadLength = 4 [(require.range) = {min: 1}];
|
||||
}
|
||||
message GetUploadFormResponse {
|
||||
message UploadForm {
|
||||
// Indicates the CDN type. 3 indicates resumable uploads using TUS
|
||||
uint32 cdn = 1;
|
||||
|
||||
// The location within the specified cdn where the finished upload can be found
|
||||
string key = 2;
|
||||
|
||||
// A map of headers to include with all upload requests. Potentially contains
|
||||
// time-limited upload credentials
|
||||
map<string, string> headers = 3;
|
||||
|
||||
// The URL to upload to with the appropriate protocol
|
||||
string signed_upload_location = 4;
|
||||
}
|
||||
|
||||
oneof outcome {
|
||||
UploadForm upload_form = 1;
|
||||
oneof response {
|
||||
common.UploadForm upload_form = 1;
|
||||
|
||||
// The provided backup auth credential presentation could not be
|
||||
// authenticated. Either, the presentation could not be verified, or
|
||||
@@ -392,7 +379,8 @@ message GetUploadFormResponse {
|
||||
errors.FailedZkAuthentication failed_authentication = 2 [(tag.reason) = "failed_authentication"];
|
||||
|
||||
// The request size was larger than the maximum supported upload size. The
|
||||
// maximum upload size is subject to change.
|
||||
// maximum upload size is subject to change and is governed by
|
||||
// `global.attachments.maxBytes`
|
||||
errors.FailedPrecondition exceeds_max_upload_length = 3 [(tag.reason) = "oversize_upload"];
|
||||
}
|
||||
}
|
||||
@@ -402,7 +390,7 @@ message CopyMediaItem {
|
||||
uint32 source_attachment_cdn = 1 [(require.range).min = 1, (require.range).max = 3];
|
||||
|
||||
// The attachment key of the object to copy into the backup
|
||||
string source_key = 2 [(require.nonEmpty) = true];
|
||||
string source_key = 2 [(require.nonEmpty) = true, (require.base64url) = true];
|
||||
|
||||
// The length of the source attachment before the encryption applied by the
|
||||
// copy operation
|
||||
@@ -437,7 +425,7 @@ message CopyMediaResponse {
|
||||
// The 15-byte media_id from the corresponding CopyMediaItem in the request
|
||||
bytes media_id = 1;
|
||||
|
||||
oneof outcome {
|
||||
oneof response {
|
||||
// The media item was successfully copied into the backup
|
||||
CopySuccess success = 2;
|
||||
|
||||
@@ -448,13 +436,13 @@ message CopyMediaResponse {
|
||||
errors.FailedZkAuthentication failed_authentication = 3 [(tag.reason) = "failed_authentication"];
|
||||
|
||||
// The source object was not found
|
||||
SourceNotFound source_not_found = 4;
|
||||
SourceNotFound source_not_found = 4 [(tag.reason) = "source_not_found"];
|
||||
|
||||
// The provided object length was incorrect
|
||||
WrongSourceLength wrong_source_length = 5;
|
||||
WrongSourceLength wrong_source_length = 5 [(tag.reason) = "wrong_source_length"];
|
||||
|
||||
// All media capacity has been consumed. Free some space to continue.
|
||||
OutOfSpace out_of_space = 6;
|
||||
OutOfSpace out_of_space = 6 [(tag.reason) = "out_of_space"];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -497,7 +485,7 @@ message ListMediaResponse {
|
||||
optional string cursor = 4;
|
||||
}
|
||||
|
||||
oneof outcome {
|
||||
oneof response {
|
||||
ListResult list_result = 1;
|
||||
|
||||
// The provided backup auth credential presentation could not be
|
||||
@@ -512,7 +500,7 @@ message DeleteAllRequest {
|
||||
SignedPresentation signed_presentation = 1;
|
||||
}
|
||||
message DeleteAllResponse {
|
||||
oneof outcome {
|
||||
oneof response {
|
||||
// The backup was successfully scheduled for deletion
|
||||
google.protobuf.Empty success = 1;
|
||||
|
||||
@@ -539,7 +527,7 @@ message DeleteMediaRequest {
|
||||
}
|
||||
|
||||
message DeleteMediaResponse {
|
||||
oneof outcome {
|
||||
oneof response {
|
||||
DeleteMediaItem deleted_item = 1;
|
||||
|
||||
// The provided backup auth credential presentation could not be
|
||||
|
||||
@@ -41,7 +41,7 @@ message EcPreKey {
|
||||
// A locally-unique identifier for this key, which will be provided by
|
||||
// peers using this key to encrypt messages so the private key can be looked
|
||||
// up.
|
||||
uint64 key_id = 1;
|
||||
uint32 key_id = 1;
|
||||
|
||||
// The public key, serialized in libsignal's elliptic-curve public key format.
|
||||
bytes public_key = 2 [(require.nonEmpty) = true];
|
||||
@@ -51,7 +51,7 @@ message EcSignedPreKey {
|
||||
// A locally-unique identifier for this key, which will be provided by
|
||||
// peers using this key to encrypt messages so the private key can be looked
|
||||
// up.
|
||||
uint64 key_id = 1;
|
||||
uint32 key_id = 1;
|
||||
|
||||
// The public key, serialized in libsignal's elliptic-curve public key format.
|
||||
bytes public_key = 2 [(require.nonEmpty) = true];
|
||||
@@ -64,7 +64,7 @@ message EcSignedPreKey {
|
||||
message KemSignedPreKey {
|
||||
// An locally-unique identifier for this key, which will be provided by peers
|
||||
// using this key to encrypt messages so the private key can be looked up.
|
||||
uint64 key_id = 1;
|
||||
uint32 key_id = 1;
|
||||
|
||||
// The public key, serialized in libsignal's Kyber1024 public key format.
|
||||
bytes public_key = 2 [(require.nonEmpty) = true];
|
||||
@@ -97,3 +97,19 @@ message ZkCredential {
|
||||
bytes credential = 2 [(require.nonEmpty) = true];
|
||||
}
|
||||
|
||||
// An upload location and credentials which may be used to upload an object
|
||||
// to an external CDN
|
||||
message UploadForm {
|
||||
// Indicates the CDN type. 3 indicates resumable uploads using TUS
|
||||
uint32 cdn = 1;
|
||||
|
||||
// The location within the specified cdn where the finished upload can be found
|
||||
string key = 2;
|
||||
|
||||
// A map of headers to include with all upload requests. Potentially contains
|
||||
// time-limited upload credentials
|
||||
map<string, string> headers = 3;
|
||||
|
||||
// The URL to upload to with the appropriate protocol
|
||||
string signed_upload_location = 4;
|
||||
}
|
||||
@@ -14,6 +14,7 @@ import "google/protobuf/empty.proto";
|
||||
import "org/signal/chat/common.proto";
|
||||
import "org/signal/chat/errors.proto";
|
||||
import "org/signal/chat/require.proto";
|
||||
import "org/signal/chat/tag.proto";
|
||||
|
||||
// Provides methods for working with pre-keys.
|
||||
service Keys {
|
||||
@@ -152,7 +153,7 @@ message GetPreKeysResponse {
|
||||
|
||||
// Either the target account was not found, no active device with the given
|
||||
// ID (if specified) was found on the target account.
|
||||
errors.NotFound target_not_found = 2;
|
||||
errors.NotFound target_not_found = 2 [(tag.reason) = "not_found"];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -163,10 +164,10 @@ message GetPreKeysAnonymousResponse {
|
||||
|
||||
// Either the target account was not found, no active device with the given
|
||||
// ID (if specified) was found on the target account.
|
||||
errors.NotFound target_not_found = 2;
|
||||
errors.NotFound target_not_found = 2 [(tag.reason) = "not_found"];
|
||||
|
||||
// The provided unidentified authorization credential was invalid
|
||||
errors.FailedUnidentifiedAuthorization failed_unidentified_authorization = 3;
|
||||
errors.FailedUnidentifiedAuthorization failed_unidentified_authorization = 3 [(tag.reason) = "failed_unidentified_authorization"];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ import "google/protobuf/empty.proto";
|
||||
import "org/signal/chat/common.proto";
|
||||
import "org/signal/chat/require.proto";
|
||||
import "org/signal/chat/errors.proto";
|
||||
import "org/signal/chat/tag.proto";
|
||||
|
||||
// Provides methods for sending "unsealed sender" messages.
|
||||
service Messages {
|
||||
@@ -153,14 +154,14 @@ message SendMessageAuthenticatedSenderResponse {
|
||||
// A list of discrepancies between the destination devices identified in a
|
||||
// request to send a message and the devices that are actually linked to an
|
||||
// account.
|
||||
MismatchedDevices mismatched_devices = 2;
|
||||
MismatchedDevices mismatched_devices = 2 [(tag.reason) = "mismatched_devices"];
|
||||
|
||||
// A description of a challenge callers must complete before sending
|
||||
// additional messages.
|
||||
ChallengeRequired challenge_required = 3;
|
||||
ChallengeRequired challenge_required = 3 [(tag.reason) = "challenge_required"];
|
||||
|
||||
// The destination account did not exist
|
||||
errors.NotFound destination_not_found = 4;
|
||||
errors.NotFound destination_not_found = 4 [(tag.reason) = "destination_not_found"];
|
||||
|
||||
}
|
||||
}
|
||||
@@ -233,13 +234,13 @@ message SendMessageResponse {
|
||||
// A list of discrepancies between the destination devices identified in a
|
||||
// request to send a message and the devices that are actually linked to an
|
||||
// account.
|
||||
MismatchedDevices mismatched_devices = 2;
|
||||
MismatchedDevices mismatched_devices = 2 [(tag.reason) = "mismatched_devices"];
|
||||
|
||||
// The provided unidentified authorization credential was invalid
|
||||
errors.FailedUnidentifiedAuthorization failed_unidentified_authorization = 3;
|
||||
errors.FailedUnidentifiedAuthorization failed_unidentified_authorization = 3 [(tag.reason) = "failed_unidentified_authorization"];
|
||||
|
||||
// The destination account did not exist
|
||||
errors.NotFound destination_not_found = 4;
|
||||
errors.NotFound destination_not_found = 4 [(tag.reason) = "destination_not_found"];
|
||||
|
||||
}
|
||||
}
|
||||
@@ -307,10 +308,10 @@ message SendMultiRecipientMessageResponse {
|
||||
// A list of sets of discrepancies between the destination devices
|
||||
// identified in a request to send a message and the devices that are
|
||||
// actually linked to a destination account.
|
||||
MultiRecipientMismatchedDevices mismatched_devices = 2;
|
||||
MultiRecipientMismatchedDevices mismatched_devices = 2 [(tag.reason) = "mismatched_devices"];
|
||||
|
||||
// The provided unidentified authorization credential was invalid
|
||||
errors.FailedUnidentifiedAuthorization failed_unidentified_authorization = 3;
|
||||
errors.FailedUnidentifiedAuthorization failed_unidentified_authorization = 3 [(tag.reason) = "failed_unidentified_authorization"];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -147,6 +147,21 @@ extend google.protobuf.FieldOptions {
|
||||
*````
|
||||
*/
|
||||
optional bool present = 70007;
|
||||
|
||||
/*
|
||||
* Requires a value of a string field to be a valid base64 URL string. The
|
||||
* string may be padded or unpadded. If the field is `optional`, this check
|
||||
* allows a value to be not set.
|
||||
*
|
||||
* ```
|
||||
* import "org/signal/chat/require.proto";
|
||||
*
|
||||
* message Data {
|
||||
* string myString = 1 [(require.base64url)];
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
optional bool base64url = 70008;
|
||||
}
|
||||
|
||||
message SizeConstraint {
|
||||
|
||||
@@ -2,14 +2,17 @@
|
||||
-- returns a list of all envelopes and their queue-local IDs
|
||||
|
||||
local queueKey = KEYS[1] -- sorted set of all Envelopes for a device, scored by queue-local ID
|
||||
local queueLockKey = KEYS[2] -- a key whose presence indicates that the queue is being persistent and must not be read
|
||||
local queueLockKey = KEYS[2] -- a key whose presence indicates that the queue is being persisted and must not be read
|
||||
local limit = ARGV[1] -- [number] the maximum number of messages to return
|
||||
local afterMessageId = ARGV[2] -- [number] a queue-local ID to exclusively start after, to support pagination. Use -1 to start at the beginning
|
||||
local bypassLock = ARGV[3] -- [string] whether to bypass the persistence lock (i.e. when fetching messages for persistence)
|
||||
|
||||
local locked = redis.call("GET", queueLockKey)
|
||||
if bypassLock ~= "true" then
|
||||
local locked = redis.call("GET", queueLockKey)
|
||||
|
||||
if locked then
|
||||
return {}
|
||||
if locked then
|
||||
return {}
|
||||
end
|
||||
end
|
||||
|
||||
if afterMessageId == "null" or afterMessageId == nil then
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
-- returns a list of queues that meet persistence criteria
|
||||
|
||||
local queueTotalIndexKey = KEYS[1] -- sorted set of all queues in the shard, by timestamp of oldest message
|
||||
local maxTime = ARGV[1] -- [number] the most recent queue timestamp that may be fetched
|
||||
local limit = ARGV[2] -- [number] the maximum number of queues to fetch
|
||||
|
||||
local results = redis.call("ZRANGE", queueTotalIndexKey, 0, maxTime, "BYSCORE", "LIMIT", 0, limit)
|
||||
|
||||
if results and next(results) then
|
||||
redis.call("ZREM", queueTotalIndexKey, unpack(results))
|
||||
end
|
||||
|
||||
return results
|
||||
@@ -3,12 +3,10 @@
|
||||
|
||||
local queueKey = KEYS[1] -- sorted set of Envelopes for a device, by queue-local ID
|
||||
local queueMetadataKey = KEYS[2] -- hash of message GUID to queue-local IDs
|
||||
local queueTotalIndexKey = KEYS[3] -- sorted set of all queues in the shard, by timestamp of oldest message
|
||||
local eventChannelKey = KEYS[4] -- pub/sub channel for message availability events
|
||||
local eventChannelKey = KEYS[3] -- pub/sub channel for message availability events
|
||||
local message = ARGV[1] -- [bytes] the Envelope to insert
|
||||
local currentTime = ARGV[2] -- [number] the message timestamp, to sort the queue in the queueTotalIndex
|
||||
local guid = ARGV[3] -- [string] the message GUID
|
||||
local eventPayload = ARGV[4] -- [bytes] a protobuf payload for a "message available" pub/sub event
|
||||
local guid = ARGV[2] -- [string] the message GUID
|
||||
local eventPayload = ARGV[3] -- [bytes] a protobuf payload for a "message available" pub/sub event
|
||||
|
||||
if redis.call("HEXISTS", queueMetadataKey, guid) == 1 then
|
||||
return tonumber(redis.call("HGET", queueMetadataKey, guid))
|
||||
@@ -22,6 +20,4 @@ redis.call("HSET", queueMetadataKey, guid, messageId)
|
||||
redis.call("EXPIRE", queueKey, 3974400) -- 46 days
|
||||
redis.call("EXPIRE", queueMetadataKey, 3974400) -- 46 days
|
||||
|
||||
redis.call("ZADD", queueTotalIndexKey, "NX", currentTime, queueKey)
|
||||
|
||||
return redis.call("SPUBLISH", eventChannelKey, eventPayload) > 0
|
||||
Loaded 100 of 147 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user