mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-12-01 00:36:47 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1fe6dac760 | ||
|
|
f12a6ff73f | ||
|
|
6eed458ceb | ||
|
|
54fb0a6acb | ||
|
|
5147d9cb6d | ||
|
|
37369929f3 | ||
|
|
4f10014902 | ||
|
|
0ef3e00ba7 | ||
|
|
2408590430 | ||
|
|
b7f4fe4d73 | ||
|
|
b811492acd | ||
|
|
a63e0e0390 | ||
|
|
5e8a0b2cfa | ||
|
|
eac75aad03 | ||
|
|
b05fbc2102 | ||
|
|
6d166fdfc5 | ||
|
|
2e36673702 | ||
|
|
0c81ffe8b7 | ||
|
|
02b9ceb4c7 | ||
|
|
775889c0b6 | ||
|
|
98f2cdaf5a | ||
|
|
ff5cc3cb4f | ||
|
|
ebecb1caec | ||
|
|
73e0aea85c | ||
|
|
1a09f5807b | ||
|
|
ec009a2bba | ||
|
|
f52c40a492 | ||
|
|
1959c059ed | ||
|
|
2d1610b075 | ||
|
|
2f76738b50 | ||
|
|
1cf174a613 | ||
|
|
d743454d07 | ||
|
|
1cd16eaa08 | ||
|
|
90e622b307 | ||
|
|
cb5cd64c05 | ||
|
|
2619569549 | ||
|
|
d306cafbcc | ||
|
|
f5ce34fb69 | ||
|
|
dbeba4f173 | ||
|
|
86f83635bc | ||
|
|
fceda00d83 | ||
|
|
9b7af00cf5 | ||
|
|
fa1281ae86 | ||
|
|
f5de4d7b71 | ||
|
|
1134df88e2 | ||
|
|
4aadabfac0 | ||
|
|
c27898a993 | ||
|
|
daa897db93 | ||
|
|
7a907bb44d | ||
|
|
d7cb219577 | ||
|
|
b28f8b0e7f | ||
|
|
51721dde50 | ||
|
|
09547ba788 | ||
|
|
3dc8acc385 | ||
|
|
0414da8c32 | ||
|
|
155450380e | ||
|
|
09bc4ef1d6 | ||
|
|
3aa4d8713c | ||
|
|
5fc926271f | ||
|
|
f435b612c9 | ||
|
|
5b78c0d3e0 | ||
|
|
6a14bf70e0 | ||
|
|
138b368951 | ||
|
|
0871d6ebc1 | ||
|
|
ad5ef76e8e | ||
|
|
2f55747601 | ||
|
|
b376458963 | ||
|
|
64ac22a918 | ||
|
|
ffb81e4ff7 | ||
|
|
01743e5c88 | ||
|
|
4ef6266e8f | ||
|
|
478a8362b8 | ||
|
|
afa1899dc9 | ||
|
|
cea2abcf6e | ||
|
|
c7d1ad56ff | ||
|
|
a5f490cc53 | ||
|
|
abe29fa6ee | ||
|
|
f6d1e566e7 | ||
|
|
9ec4f0b2f5 | ||
|
|
1678045ce4 | ||
|
|
7286e724dc | ||
|
|
e59a1e9efd | ||
|
|
097bedcb9b | ||
|
|
907ff89011 | ||
|
|
08faa0c009 |
No files matched your search
@@ -11,8 +11,8 @@ jobs:
|
||||
contents: write
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1
|
||||
- uses: actions/setup-java@9704b39bf258b59bc04b50fa2dd55e9ed76b47a8 # v4.1.0
|
||||
- uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7
|
||||
- uses: actions/setup-java@99b8673ff64fbf99d8d325f52d9a5bdedb8483e9 # v4.2.1
|
||||
with:
|
||||
distribution: 'temurin'
|
||||
java-version: '21'
|
||||
|
||||
@@ -13,13 +13,13 @@ jobs:
|
||||
id-token: write
|
||||
contents: read
|
||||
steps:
|
||||
- uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1
|
||||
- uses: actions/setup-java@9704b39bf258b59bc04b50fa2dd55e9ed76b47a8 # v4.1.0
|
||||
- uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7
|
||||
- uses: actions/setup-java@99b8673ff64fbf99d8d325f52d9a5bdedb8483e9 # v4.2.1
|
||||
with:
|
||||
distribution: 'temurin'
|
||||
java-version: '21'
|
||||
cache: 'maven'
|
||||
- uses: aws-actions/configure-aws-credentials@e3dd6a429d7300a6a4c196c26e071d42e0343502 #v4.0.2
|
||||
- uses: aws-actions/configure-aws-credentials@5579c002bb4778aa43395ef1df492868a9a1c83f # v4.0.2
|
||||
name: Configure AWS credentials from Test account
|
||||
with:
|
||||
role-to-assume: ${{ vars.AWS_ROLE }}
|
||||
|
||||
@@ -11,9 +11,9 @@ jobs:
|
||||
container: ubuntu:22.04
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1
|
||||
- uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7
|
||||
- name: Set up JDK 21
|
||||
uses: actions/setup-java@9704b39bf258b59bc04b50fa2dd55e9ed76b47a8 # v4.1.0
|
||||
uses: actions/setup-java@99b8673ff64fbf99d8d325f52d9a5bdedb8483e9 # v4.2.1
|
||||
with:
|
||||
distribution: 'temurin'
|
||||
java-version: 21
|
||||
|
||||
Vendored
BIN
Binary file not shown.
+4
-4
@@ -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.4/apache-maven-3.9.4-bin.zip
|
||||
wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar
|
||||
distributionSha256Sum=e896b60329a71b719d77bb4388b251a50aebcd73c62f69d510c858ce360afe0f
|
||||
wrapperSha256Sum=e63a53cfb9c4d291ebe3c2b0edacb7622bbc480326beaa5a0456e412f52f066a
|
||||
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.8/apache-maven-3.9.8-bin.zip
|
||||
wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.3.2/maven-wrapper-3.3.2.jar
|
||||
distributionSha256Sum=8351955a9acf2f83c136c4eee0f6db894ab6265fdbe0a94b32a380307dbaa3e1
|
||||
wrapperSha256Sum=3d8f20ce6103913be8b52aef6d994e0c54705fb527324ceb9b835b338739c7a8
|
||||
@@ -28,7 +28,7 @@
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>3.1.2</version>
|
||||
<version>3.3.0</version>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>**</exclude>
|
||||
@@ -39,7 +39,7 @@
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-failsafe-plugin</artifactId>
|
||||
<version>3.1.2</version>
|
||||
<version>3.3.0</version>
|
||||
<configuration>
|
||||
<additionalClasspathElements>
|
||||
<additionalClasspathElement>${project.basedir}/.libs/software.amazon.awssdk-sso.jar</additionalClasspathElement>
|
||||
|
||||
@@ -50,6 +50,7 @@ import org.whispersystems.textsecuregcm.entities.RegistrationRequest;
|
||||
import org.whispersystems.textsecuregcm.http.FaultTolerantHttpClient;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.util.HeaderUtils;
|
||||
import org.whispersystems.textsecuregcm.util.HttpUtils;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
import javax.validation.ConstraintViolation;
|
||||
|
||||
@@ -249,7 +250,7 @@ public final class Operations {
|
||||
public Pair<Integer, Void> executeExpectSuccess() {
|
||||
final Pair<Integer, Void> execute = execute();
|
||||
Validate.isTrue(
|
||||
execute.getLeft() >= 200 && execute.getLeft() < 300,
|
||||
HttpUtils.isSuccessfulResponse(execute.getLeft()),
|
||||
"Unexpected response code: %d",
|
||||
execute.getLeft());
|
||||
return execute;
|
||||
@@ -257,6 +258,10 @@ public final class Operations {
|
||||
|
||||
public <T> T executeExpectSuccess(final Class<T> expectedType) {
|
||||
final Pair<Integer, T> execute = execute(expectedType);
|
||||
Validate.isTrue(
|
||||
HttpUtils.isSuccessfulResponse(execute.getLeft()),
|
||||
"Unexpected response code: %d : %s",
|
||||
execute.getLeft(), execute.getRight());
|
||||
return requireNonNull(execute.getRight());
|
||||
}
|
||||
|
||||
|
||||
@@ -126,7 +126,7 @@ public class TestUser {
|
||||
}
|
||||
|
||||
public AccountAttributes accountAttributes() {
|
||||
return new AccountAttributes(true, registrationId, pniRegistrationId, "".getBytes(StandardCharsets.UTF_8), "", true, new Device.DeviceCapabilities(false, false, false))
|
||||
return new AccountAttributes(true, registrationId, pniRegistrationId, "".getBytes(StandardCharsets.UTF_8), "", true, new Device.DeviceCapabilities(false, false, false, false))
|
||||
.withUnidentifiedAccessKey(unidentifiedAccessKey)
|
||||
.withRecoveryPassword(registrationPassword);
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
|
||||
package org.signal.integration;
|
||||
|
||||
import io.micrometer.common.util.StringUtils;
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.whispersystems.textsecuregcm.entities.CreateVerificationSessionRequest;
|
||||
@@ -29,6 +30,8 @@ public class RegistrationTest {
|
||||
.executeExpectSuccess(VerificationSessionResponse.class);
|
||||
|
||||
final String sessionId = verificationSessionResponse.id();
|
||||
Assertions.assertTrue(StringUtils.isNotBlank(sessionId));
|
||||
|
||||
final String pushChallenge = Operations.peekVerificationSessionPushChallenge(sessionId);
|
||||
|
||||
// supply push challenge
|
||||
|
||||
@@ -38,40 +38,41 @@
|
||||
|
||||
<properties>
|
||||
<aws.sdk2.version>2.23.8</aws.sdk2.version>
|
||||
<braintree.version>3.27.0</braintree.version>
|
||||
<commons-csv.version>1.10.0</commons-csv.version>
|
||||
<commons-io.version>2.14.0</commons-io.version>
|
||||
<dropwizard.version>3.0.6</dropwizard.version>
|
||||
<braintree.version>3.34.0</braintree.version>
|
||||
<commons-csv.version>1.11.0</commons-csv.version>
|
||||
<commons-io.version>2.16.1</commons-io.version>
|
||||
<dropwizard.version>3.0.7</dropwizard.version>
|
||||
<dropwizard-metrics-datadog.version>1.1.13</dropwizard-metrics-datadog.version>
|
||||
<dynamodblocal.version>1.23.0</dynamodblocal.version>
|
||||
<google-cloud-libraries.version>26.33.0</google-cloud-libraries.version>
|
||||
<grpc.version>1.61.1</grpc.version> <!-- should be kept in sync with the value from Google libraries-bom -->
|
||||
<gson.version>2.10.1</gson.version>
|
||||
<gson.version>2.11.0</gson.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.16.0</jackson.version>
|
||||
<jackson.version>2.17.2</jackson.version>
|
||||
<jaxb.version>2.3.1</jaxb.version>
|
||||
<junit-pioneer.version>2.1.0</junit-pioneer.version>
|
||||
<junit-pioneer.version>2.2.0</junit-pioneer.version>
|
||||
<jsr305.version>3.0.2</jsr305.version>
|
||||
<kotlin.version>1.9.10</kotlin.version>
|
||||
<kotlin.version>1.9.24</kotlin.version>
|
||||
<kotlinx-serialization.version>1.5.1</kotlinx-serialization.version>
|
||||
<lettuce.version>6.3.2.RELEASE</lettuce.version>
|
||||
<libphonenumber.version>8.13.23</libphonenumber.version>
|
||||
<libphonenumber.version>8.13.40</libphonenumber.version>
|
||||
<logstash.logback.version>7.3</logstash.logback.version>
|
||||
<log4j-bom.version>2.21.0</log4j-bom.version>
|
||||
<log4j-bom.version>2.23.1</log4j-bom.version>
|
||||
<luajava.version>3.4.0</luajava.version>
|
||||
<micrometer.version>1.12.4</micrometer.version>
|
||||
<netty.version>4.1.108.Final</netty.version>
|
||||
<micrometer.version>1.13.2</micrometer.version>
|
||||
<netty.version>4.1.111.Final</netty.version>
|
||||
<opentest4j.version>1.3.0</opentest4j.version>
|
||||
<protobuf.version>3.25.2</protobuf.version> <!-- should be kept in sync with the value from Google libraries-bom -->
|
||||
<pushy.version>0.15.4</pushy.version>
|
||||
<reactive.grpc.version>1.2.4</reactive.grpc.version>
|
||||
<reactor-bom.version>2023.0.4</reactor-bom.version> <!-- 3.6.x, see https://github.com/reactor/reactor#bom-versioning-scheme -->
|
||||
<reactor-bom.version>2023.0.8</reactor-bom.version> <!-- 3.6.x, see https://github.com/reactor/reactor#bom-versioning-scheme -->
|
||||
<resilience4j.version>2.2.0</resilience4j.version>
|
||||
<semver4j.version>3.1.0</semver4j.version>
|
||||
<slf4j.version>2.0.9</slf4j.version>
|
||||
<slf4j.version>2.0.13</slf4j.version>
|
||||
<stripe.version>23.10.0</stripe.version>
|
||||
<swagger.version>2.2.17</swagger.version>
|
||||
<swagger.version>2.2.22</swagger.version>
|
||||
|
||||
<!-- 21.0.3_9-jre-jammy -->
|
||||
<docker.image.sha256>434c26bd14f3208b9e739277e2679c2c7ef3f85d4a4f32c5a27b12a7fc206b09</docker.image.sha256>
|
||||
@@ -278,7 +279,7 @@
|
||||
<dependency>
|
||||
<groupId>org.signal</groupId>
|
||||
<artifactId>libsignal-server</artifactId>
|
||||
<version>0.45.0</version>
|
||||
<version>0.51.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.signal.forks</groupId>
|
||||
@@ -302,6 +303,12 @@
|
||||
<artifactId>httpclient</artifactId>
|
||||
<version>${httpclient.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.amazonaws</groupId>
|
||||
<artifactId>DynamoDBLocal</artifactId>
|
||||
<version>${dynamodblocal.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
@@ -383,7 +390,7 @@
|
||||
<plugin>
|
||||
<groupId>com.google.cloud.tools</groupId>
|
||||
<artifactId>jib-maven-plugin</artifactId>
|
||||
<version>3.4.0</version>
|
||||
<version>3.4.3</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</pluginManagement>
|
||||
@@ -424,7 +431,7 @@
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.11.0</version>
|
||||
<version>3.13.0</version>
|
||||
<configuration>
|
||||
<release>21</release>
|
||||
</configuration>
|
||||
@@ -433,7 +440,7 @@
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-jar-plugin</artifactId>
|
||||
<version>3.3.0</version>
|
||||
<version>3.4.2</version>
|
||||
<configuration>
|
||||
<archive>
|
||||
<manifest>
|
||||
@@ -446,7 +453,7 @@
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-dependency-plugin</artifactId>
|
||||
<version>3.3.0</version>
|
||||
<version>3.7.1</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>copy</id>
|
||||
@@ -466,7 +473,7 @@
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>3.1.2</version>
|
||||
<version>3.3.0</version>
|
||||
<configuration>
|
||||
<systemProperties>
|
||||
<property>
|
||||
@@ -480,7 +487,7 @@
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-enforcer-plugin</artifactId>
|
||||
<version>3.3.0</version>
|
||||
<version>3.5.0</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
@@ -501,7 +508,7 @@
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-install-plugin</artifactId>
|
||||
<version>3.1.1</version>
|
||||
<version>3.1.2</version>
|
||||
<configuration>
|
||||
<skip>true</skip>
|
||||
</configuration>
|
||||
@@ -510,7 +517,7 @@
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-deploy-plugin</artifactId>
|
||||
<version>3.1.1</version>
|
||||
<version>3.1.2</version>
|
||||
<configuration>
|
||||
<skip>true</skip>
|
||||
</configuration>
|
||||
|
||||
@@ -91,8 +91,7 @@ currentReportingKey.secret: AAAAAAAAAAA=
|
||||
currentReportingKey.salt: AAAAAAAAAAA=
|
||||
|
||||
turn.secret: AAAAAAAAAAA=
|
||||
turn.cloudflare.username: ABCDEFGHIJKLM
|
||||
turn.cloudflare.password: NOPQRSTUVWXYZ
|
||||
turn.cloudflare.apiToken: ABCDEFGHIJKLM
|
||||
|
||||
linkDevice.secret: AAAAAAAAAAA=
|
||||
|
||||
|
||||
@@ -126,6 +126,9 @@ dynamoDbTables:
|
||||
tableName: Example_RemoteConfig
|
||||
reportMessage:
|
||||
tableName: Example_ReportMessage
|
||||
scheduledJobs:
|
||||
tableName: Example_ScheduledJobs
|
||||
expiration: P7D
|
||||
subscriptions:
|
||||
tableName: Example_Subscriptions
|
||||
clientPublicKeys:
|
||||
@@ -429,10 +432,15 @@ registrationService:
|
||||
turn:
|
||||
secret: secret://turn.secret
|
||||
cloudflare:
|
||||
username: secret://turn.cloudflare.username
|
||||
password: secret://turn.cloudflare.password
|
||||
apiToken: secret://turn.cloudflare.apiToken
|
||||
endpoint: https://rtc.live.cloudflare.com/v1/turn/keys/LMNOP/credentials/generate
|
||||
urls:
|
||||
- turns:turn.cloudflare.example.com:443?transport=tcp
|
||||
- turn:turn.example.com:80
|
||||
urlsWithIps:
|
||||
- turn:%s
|
||||
- turn:%s:80?transport=tcp
|
||||
- turns:%s:443?transport=tcp
|
||||
ttl: 86400
|
||||
hostname: turn.cloudflare.example.com
|
||||
|
||||
linkDevice:
|
||||
|
||||
+20
-8
@@ -12,7 +12,7 @@
|
||||
|
||||
<properties>
|
||||
<firebase-admin.version>9.2.0</firebase-admin.version>
|
||||
<java-uuid-generator.version>4.3.0</java-uuid-generator.version>
|
||||
<java-uuid-generator.version>5.1.0</java-uuid-generator.version>
|
||||
<sqlite4java.version>1.0.392</sqlite4java.version>
|
||||
</properties>
|
||||
|
||||
@@ -393,11 +393,24 @@
|
||||
<artifactId>libphonenumber</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- Provides tools for mapping phone numbers to time zones, which is helpful for scheduling push notifications
|
||||
during waking hours -->
|
||||
<dependency>
|
||||
<groupId>com.googlecode.libphonenumber</groupId>
|
||||
<artifactId>geocoder</artifactId>
|
||||
<version>2.234</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>net.sourceforge.argparse4j</groupId>
|
||||
<artifactId>argparse4j</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>io.netty</groupId>
|
||||
<artifactId>netty-codec-haproxy</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.glassfish.jersey.test-framework</groupId>
|
||||
<artifactId>jersey-test-framework-core</artifactId>
|
||||
@@ -458,7 +471,6 @@
|
||||
<dependency>
|
||||
<groupId>com.amazonaws</groupId>
|
||||
<artifactId>DynamoDBLocal</artifactId>
|
||||
<version>1.23.0</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
@@ -507,7 +519,7 @@
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-shade-plugin</artifactId>
|
||||
<version>3.5.1</version>
|
||||
<version>3.6.0</version>
|
||||
<configuration>
|
||||
<createDependencyReducedPom>true</createDependencyReducedPom>
|
||||
<filters>
|
||||
@@ -542,7 +554,7 @@
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-assembly-plugin</artifactId>
|
||||
<version>3.6.0</version>
|
||||
<version>3.7.1</version>
|
||||
<configuration>
|
||||
<descriptors>
|
||||
<descriptor>assembly.xml</descriptor>
|
||||
@@ -562,7 +574,7 @@
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>properties-maven-plugin</artifactId>
|
||||
<version>1.2.0</version>
|
||||
<version>1.2.1</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>read-deploy-configuration</id>
|
||||
@@ -673,7 +685,7 @@
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>templating-maven-plugin</artifactId>
|
||||
<version>1.0.0</version>
|
||||
<version>3.0.0</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>filter-src</id>
|
||||
@@ -687,7 +699,7 @@
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>3.1.2</version>
|
||||
<version>3.3.0</version>
|
||||
<configuration>
|
||||
<!-- work around PATCH not being a supported method on HttpUrlConnection -->
|
||||
<argLine>--add-opens=java.base/java.net=ALL-UNNAMED</argLine>
|
||||
@@ -709,7 +721,7 @@
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>exec-maven-plugin</artifactId>
|
||||
<version>3.1.0</version>
|
||||
<version>3.3.0</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>check-all-service-config</id>
|
||||
|
||||
@@ -28,6 +28,11 @@ import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.binder.grpc.MetricCollectingServerInterceptor;
|
||||
import io.micrometer.core.instrument.binder.jvm.ExecutorServiceMetrics;
|
||||
import io.netty.channel.local.LocalAddress;
|
||||
import io.netty.channel.socket.nio.NioDatagramChannel;
|
||||
import io.netty.channel.socket.nio.NioSocketChannel;
|
||||
import io.netty.resolver.ResolvedAddressTypes;
|
||||
import io.netty.resolver.dns.DnsNameResolver;
|
||||
import io.netty.resolver.dns.DnsNameResolverBuilder;
|
||||
import java.io.FileInputStream;
|
||||
import java.net.http.HttpClient;
|
||||
import java.security.KeyStore;
|
||||
@@ -36,6 +41,7 @@ import java.security.cert.X509Certificate;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.EnumSet;
|
||||
import java.util.List;
|
||||
@@ -72,6 +78,7 @@ import org.whispersystems.textsecuregcm.attachments.TusAttachmentGenerator;
|
||||
import org.whispersystems.textsecuregcm.auth.AccountAuthenticator;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
|
||||
import org.whispersystems.textsecuregcm.auth.CertificateGenerator;
|
||||
import org.whispersystems.textsecuregcm.auth.CloudflareTurnCredentialsManager;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
|
||||
import org.whispersystems.textsecuregcm.auth.PhoneVerificationTokenManager;
|
||||
import org.whispersystems.textsecuregcm.auth.RegistrationLockVerificationManager;
|
||||
@@ -182,7 +189,6 @@ import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
|
||||
import org.whispersystems.textsecuregcm.push.FcmSender;
|
||||
import org.whispersystems.textsecuregcm.push.MessageSender;
|
||||
import org.whispersystems.textsecuregcm.push.ProvisioningManager;
|
||||
import org.whispersystems.textsecuregcm.push.PushLatencyManager;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
|
||||
import org.whispersystems.textsecuregcm.push.ReceiptSender;
|
||||
import org.whispersystems.textsecuregcm.redis.ConnectionEventLogger;
|
||||
@@ -246,7 +252,6 @@ import org.whispersystems.textsecuregcm.workers.CertificateCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.CheckDynamicConfigurationCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.DeleteUserCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.MessagePersisterServiceCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.ProcessPushNotificationFeedbackCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.RemoveExpiredAccountsCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.RemoveExpiredBackupsCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.RemoveExpiredLinkedDevicesCommand;
|
||||
@@ -307,7 +312,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
bootstrap.addCommand(new RemoveExpiredUsernameHoldsCommand(Clock.systemUTC()));
|
||||
bootstrap.addCommand(new RemoveExpiredBackupsCommand(Clock.systemUTC()));
|
||||
bootstrap.addCommand(new BackupMetricsCommand(Clock.systemUTC()));
|
||||
bootstrap.addCommand(new ProcessPushNotificationFeedbackCommand(Clock.systemUTC()));
|
||||
bootstrap.addCommand(new RemoveExpiredLinkedDevicesCommand());
|
||||
}
|
||||
|
||||
@@ -537,9 +541,24 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
.workQueue(new SynchronousQueue<>())
|
||||
.keepAliveTime(io.dropwizard.util.Duration.seconds(60L))
|
||||
.build();
|
||||
ExecutorService cloudflareTurnHttpExecutor = environment.lifecycle()
|
||||
.executorService(name(getClass(), "cloudflareTurn-%d"))
|
||||
.maxThreads(2)
|
||||
.minThreads(2)
|
||||
.build();
|
||||
|
||||
ScheduledExecutorService subscriptionProcessorRetryExecutor = environment.lifecycle()
|
||||
.scheduledExecutorService(name(getClass(), "subscriptionProcessorRetry-%d")).threads(1).build();
|
||||
ScheduledExecutorService cloudflareTurnRetryExecutor = environment.lifecycle()
|
||||
.scheduledExecutorService(name(getClass(), "cloudflareTurnRetry-%d")).threads(1).build();
|
||||
|
||||
final ManagedNioEventLoopGroup dnsResolutionEventLoopGroup = new ManagedNioEventLoopGroup();
|
||||
final DnsNameResolver cloudflareDnsResolver = new DnsNameResolverBuilder(dnsResolutionEventLoopGroup.next())
|
||||
.resolvedAddressTypes(ResolvedAddressTypes.IPV6_PREFERRED)
|
||||
.completeOncePreferredResolved(false)
|
||||
.channelType(NioDatagramChannel.class)
|
||||
.socketChannelType(NioSocketChannel.class)
|
||||
.build();
|
||||
|
||||
ExternalServiceCredentialsGenerator directoryV2CredentialsGenerator = DirectoryV2Controller.credentialsGenerator(
|
||||
config.getDirectoryV2Configuration().getDirectoryV2ClientConfiguration());
|
||||
@@ -575,7 +594,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
recurringJobExecutor,
|
||||
config.getClientReleaseConfiguration().refreshInterval(),
|
||||
Clock.systemUTC());
|
||||
PushLatencyManager pushLatencyManager = new PushLatencyManager(metricsCluster, clientReleaseManager);
|
||||
ReportMessageManager reportMessageManager = new ReportMessageManager(reportMessageDynamoDb, rateLimitersCluster,
|
||||
config.getReportMessageConfiguration().getCounterTtl());
|
||||
MessagesManager messagesManager = new MessagesManager(messagesDynamoDb, messagesCache, reportMessageManager,
|
||||
@@ -595,8 +613,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
FcmSender fcmSender = new FcmSender(fcmSenderExecutor, config.getFcmConfiguration().credentials().value());
|
||||
ApnPushNotificationScheduler apnPushNotificationScheduler = new ApnPushNotificationScheduler(pushSchedulerCluster,
|
||||
apnSender, accountsManager, 0);
|
||||
PushNotificationManager pushNotificationManager = new PushNotificationManager(accountsManager, apnSender, fcmSender,
|
||||
apnPushNotificationScheduler, pushLatencyManager);
|
||||
PushNotificationManager pushNotificationManager =
|
||||
new PushNotificationManager(accountsManager, apnSender, fcmSender, apnPushNotificationScheduler);
|
||||
RateLimiters rateLimiters = RateLimiters.createAndValidate(config.getLimitsConfiguration(),
|
||||
dynamicConfigurationManager, rateLimitersCluster);
|
||||
ProvisioningManager provisioningManager = new ProvisioningManager(
|
||||
@@ -628,12 +646,24 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
|
||||
final AccountAuthenticator accountAuthenticator = new AccountAuthenticator(accountsManager);
|
||||
|
||||
final MessageSender messageSender = new MessageSender(clientPresenceManager, messagesManager,
|
||||
pushNotificationManager,
|
||||
pushLatencyManager);
|
||||
final MessageSender messageSender =
|
||||
new MessageSender(clientPresenceManager, messagesManager, pushNotificationManager);
|
||||
final ReceiptSender receiptSender = new ReceiptSender(accountsManager, messageSender, receiptSenderExecutor);
|
||||
final TurnTokenGenerator turnTokenGenerator = new TurnTokenGenerator(dynamicConfigurationManager,
|
||||
config.getTurnConfiguration().secret().value(), config.getTurnConfiguration().cloudflare());
|
||||
config.getTurnConfiguration().secret().value());
|
||||
final CloudflareTurnCredentialsManager cloudflareTurnCredentialsManager = new CloudflareTurnCredentialsManager(
|
||||
config.getTurnConfiguration().cloudflare().apiToken().value(),
|
||||
config.getTurnConfiguration().cloudflare().endpoint(),
|
||||
config.getTurnConfiguration().cloudflare().ttl(),
|
||||
config.getTurnConfiguration().cloudflare().urls(),
|
||||
config.getTurnConfiguration().cloudflare().urlsWithIps(),
|
||||
config.getTurnConfiguration().cloudflare().hostname(),
|
||||
config.getTurnConfiguration().cloudflare().circuitBreaker(),
|
||||
cloudflareTurnHttpExecutor,
|
||||
config.getTurnConfiguration().cloudflare().retry(),
|
||||
cloudflareTurnRetryExecutor,
|
||||
cloudflareDnsResolver
|
||||
);
|
||||
|
||||
final CardinalityEstimator messageByteLimitCardinalityEstimator = new CardinalityEstimator(
|
||||
rateLimitersCluster,
|
||||
@@ -837,7 +867,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
}
|
||||
};
|
||||
|
||||
@Nullable final X509Certificate noiseWebSocketTlsCertificate;
|
||||
@Nullable final X509Certificate[] noiseWebSocketTlsCertificateChain;
|
||||
@Nullable final PrivateKey noiseWebSocketTlsPrivateKey;
|
||||
|
||||
if (config.getNoiseWebSocketTunnelConfiguration().tlsKeyStoreFile() != null &&
|
||||
@@ -851,11 +881,13 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
final KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(config.getNoiseWebSocketTunnelConfiguration().tlsKeyStoreEntryAlias(),
|
||||
new KeyStore.PasswordProtection(config.getNoiseWebSocketTunnelConfiguration().tlsKeyStorePassword().value().toCharArray()));
|
||||
|
||||
noiseWebSocketTlsCertificate = (X509Certificate) privateKeyEntry.getCertificate();
|
||||
noiseWebSocketTlsCertificateChain =
|
||||
Arrays.copyOf(privateKeyEntry.getCertificateChain(), privateKeyEntry.getCertificateChain().length, X509Certificate[].class);
|
||||
|
||||
noiseWebSocketTlsPrivateKey = privateKeyEntry.getPrivateKey();
|
||||
}
|
||||
} else {
|
||||
noiseWebSocketTlsCertificate = null;
|
||||
noiseWebSocketTlsCertificateChain = null;
|
||||
noiseWebSocketTlsPrivateKey = null;
|
||||
}
|
||||
|
||||
@@ -870,7 +902,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
|
||||
final NoiseWebSocketTunnelServer noiseWebSocketTunnelServer = new NoiseWebSocketTunnelServer(
|
||||
config.getNoiseWebSocketTunnelConfiguration().port(),
|
||||
new X509Certificate[] { noiseWebSocketTlsCertificate },
|
||||
noiseWebSocketTlsCertificateChain,
|
||||
noiseWebSocketTlsPrivateKey,
|
||||
noiseWebSocketEventLoopGroup,
|
||||
noiseWebSocketDelegatedTaskExecutor,
|
||||
@@ -883,6 +915,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
config.getNoiseWebSocketTunnelConfiguration().recognizedProxySecret().value());
|
||||
|
||||
environment.lifecycle().manage(localEventLoopGroup);
|
||||
environment.lifecycle().manage(dnsResolutionEventLoopGroup);
|
||||
environment.lifecycle().manage(anonymousGrpcServer);
|
||||
environment.lifecycle().manage(authenticatedGrpcServer);
|
||||
environment.lifecycle().manage(noiseWebSocketEventLoopGroup);
|
||||
@@ -1014,7 +1047,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
new AttachmentControllerV4(rateLimiters, gcsAttachmentGenerator, tusAttachmentGenerator,
|
||||
experimentEnrollmentManager),
|
||||
new ArchiveController(backupAuthManager, backupManager),
|
||||
new CallRoutingController(rateLimiters, callRouter, turnTokenGenerator, experimentEnrollmentManager),
|
||||
new CallRoutingController(rateLimiters, callRouter, turnTokenGenerator, experimentEnrollmentManager, cloudflareTurnCredentialsManager),
|
||||
new CallLinkController(rateLimiters, callingGenericZkSecretParams),
|
||||
new CertificateController(new CertificateGenerator(config.getDeliveryCertificate().certificate().value(),
|
||||
config.getDeliveryCertificate().ecPrivateKey(), config.getDeliveryCertificate().expiresDays()),
|
||||
|
||||
+3
-2
@@ -108,9 +108,10 @@ public class AccountAuthenticator implements Authenticator<BasicCredentials, Aut
|
||||
SaltedTokenHash.generateFor(basicCredentials.getPassword())); // new credentials have current version
|
||||
}
|
||||
return Optional.of(new AuthenticatedAccount(authenticatedAccount, device.get()));
|
||||
} else {
|
||||
failureReason = "incorrectPassword";
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
return Optional.empty();
|
||||
} catch (IllegalArgumentException | InvalidAuthorizationHeaderException iae) {
|
||||
failureReason = "invalidHeader";
|
||||
return Optional.empty();
|
||||
|
||||
+1
-1
@@ -16,5 +16,5 @@ import java.lang.annotation.Target;
|
||||
*/
|
||||
@Target(ElementType.METHOD)
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface ChangesDeviceEnabledState {
|
||||
public @interface ChangesLinkedDevices {
|
||||
}
|
||||
+116
@@ -0,0 +1,116 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.auth;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import io.netty.resolver.dns.DnsNameResolver;
|
||||
import java.io.IOException;
|
||||
import java.net.Inet6Address;
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import javax.ws.rs.core.Response;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.configuration.CircuitBreakerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.RetryConfiguration;
|
||||
import org.whispersystems.textsecuregcm.http.FaultTolerantHttpClient;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
|
||||
public class CloudflareTurnCredentialsManager {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(CloudflareTurnCredentialsManager.class);
|
||||
|
||||
private final List<String> cloudflareTurnUrls;
|
||||
private final List<String> cloudflareTurnUrlsWithIps;
|
||||
private final String cloudflareTurnHostname;
|
||||
private final HttpRequest request;
|
||||
|
||||
private final FaultTolerantHttpClient cloudflareTurnClient;
|
||||
private final DnsNameResolver dnsNameResolver;
|
||||
|
||||
record CredentialRequest(long ttl) {}
|
||||
|
||||
record CloudflareTurnResponse(IceServer iceServers) {
|
||||
|
||||
record IceServer(
|
||||
String username,
|
||||
String credential,
|
||||
List<String> urls) {
|
||||
}
|
||||
}
|
||||
|
||||
public CloudflareTurnCredentialsManager(final String cloudflareTurnApiToken,
|
||||
final String cloudflareTurnEndpoint, final long cloudflareTurnTtl, final List<String> cloudflareTurnUrls,
|
||||
final List<String> cloudflareTurnUrlsWithIps, final String cloudflareTurnHostname,
|
||||
final CircuitBreakerConfiguration circuitBreaker, final ExecutorService executor, final RetryConfiguration retry,
|
||||
final ScheduledExecutorService retryExecutor, final DnsNameResolver dnsNameResolver) {
|
||||
|
||||
this.cloudflareTurnClient = FaultTolerantHttpClient.newBuilder()
|
||||
.withName("cloudflare-turn")
|
||||
.withCircuitBreaker(circuitBreaker)
|
||||
.withExecutor(executor)
|
||||
.withRetry(retry)
|
||||
.withRetryExecutor(retryExecutor)
|
||||
.build();
|
||||
this.cloudflareTurnUrls = cloudflareTurnUrls;
|
||||
this.cloudflareTurnUrlsWithIps = cloudflareTurnUrlsWithIps;
|
||||
this.cloudflareTurnHostname = cloudflareTurnHostname;
|
||||
this.dnsNameResolver = dnsNameResolver;
|
||||
|
||||
try {
|
||||
final String body = SystemMapper.jsonMapper().writeValueAsString(new CredentialRequest(cloudflareTurnTtl));
|
||||
this.request = HttpRequest.newBuilder()
|
||||
.uri(URI.create(cloudflareTurnEndpoint))
|
||||
.header("Content-Type", "application/json")
|
||||
.header("Authorization", String.format("Bearer %s", cloudflareTurnApiToken))
|
||||
.POST(HttpRequest.BodyPublishers.ofString(body))
|
||||
.build();
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new IllegalArgumentException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public TurnToken retrieveFromCloudflare() throws IOException {
|
||||
final List<String> cloudflareTurnComposedUrls;
|
||||
try {
|
||||
cloudflareTurnComposedUrls = dnsNameResolver.resolveAll(cloudflareTurnHostname).get().stream()
|
||||
.map(i -> switch (i) {
|
||||
case Inet6Address i6 -> "[" + i6.getHostAddress() + "]";
|
||||
default -> i.getHostAddress();
|
||||
})
|
||||
.flatMap(i -> cloudflareTurnUrlsWithIps.stream().map(u -> u.formatted(i)))
|
||||
.toList();
|
||||
} catch (Exception e) {
|
||||
throw new IOException(e);
|
||||
}
|
||||
|
||||
final HttpResponse<String> response;
|
||||
try {
|
||||
response = cloudflareTurnClient.sendAsync(request, HttpResponse.BodyHandlers.ofString()).join();
|
||||
} catch (CompletionException e) {
|
||||
logger.warn("failed to make http request to Cloudflare Turn: {}", e.getMessage());
|
||||
throw new IOException(ExceptionUtils.unwrap(e));
|
||||
}
|
||||
|
||||
if (response.statusCode() != Response.Status.CREATED.getStatusCode()) {
|
||||
logger.warn("failure request credentials from Cloudflare Turn (code={}): {}", response.statusCode(), response);
|
||||
throw new IOException("Cloudflare Turn http failure : " + response.statusCode());
|
||||
}
|
||||
|
||||
final CloudflareTurnResponse cloudflareTurnResponse = SystemMapper.jsonMapper()
|
||||
.readValue(response.body(), CloudflareTurnResponse.class);
|
||||
|
||||
return new TurnToken(cloudflareTurnResponse.iceServers().username(),
|
||||
cloudflareTurnResponse.iceServers().credential(),
|
||||
cloudflareTurnUrls, cloudflareTurnComposedUrls, cloudflareTurnHostname);
|
||||
}
|
||||
}
|
||||
+3
-6
@@ -11,26 +11,23 @@ import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import javax.ws.rs.core.SecurityContext;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
class ContainerRequestUtil {
|
||||
|
||||
private static Map<Byte, Boolean> buildDevicesEnabledMap(final Account account) {
|
||||
return account.getDevices().stream().collect(Collectors.toMap(Device::getId, Device::isEnabled));
|
||||
}
|
||||
|
||||
/**
|
||||
* A read-only subset of the authenticated Account object, to enforce that filter-based consumers do not perform
|
||||
* account modifying operations.
|
||||
*/
|
||||
record AccountInfo(UUID accountId, String e164, Map<Byte, Boolean> devicesEnabled) {
|
||||
record AccountInfo(UUID accountId, String e164, Set<Byte> deviceIds) {
|
||||
|
||||
static AccountInfo fromAccount(final Account account) {
|
||||
return new AccountInfo(
|
||||
account.getUuid(),
|
||||
account.getNumber(),
|
||||
buildDevicesEnabledMap(account));
|
||||
account.getDevices().stream().map(Device::getId).collect(Collectors.toSet()));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+27
-31
@@ -8,7 +8,6 @@ package org.whispersystems.textsecuregcm.auth;
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Collectors;
|
||||
@@ -18,76 +17,73 @@ import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
|
||||
/**
|
||||
* This {@link WebsocketRefreshRequirementProvider} observes intra-request changes in {@link Account#isEnabled()} and
|
||||
* {@link Device#isEnabled()}.
|
||||
* <p>
|
||||
* If a change in {@link Account#isEnabled()} or any associated {@link Device#isEnabled()} is observed, then any active
|
||||
* WebSocket connections for the account must be closed in order for clients to get a refreshed
|
||||
* This {@link WebsocketRefreshRequirementProvider} observes intra-request changes in devices linked to an
|
||||
* {@link Account} and triggers a WebSocket refresh if that set changes. If a change in linked devices is observed, then
|
||||
* any active WebSocket connections for the account must be closed in order for clients to get a refreshed
|
||||
* {@link io.dropwizard.auth.Auth} object with a current device list.
|
||||
*
|
||||
* @see AuthenticatedAccount
|
||||
*/
|
||||
public class AuthEnablementRefreshRequirementProvider implements WebsocketRefreshRequirementProvider {
|
||||
public class LinkedDeviceRefreshRequirementProvider implements WebsocketRefreshRequirementProvider {
|
||||
|
||||
private final AccountsManager accountsManager;
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(AuthEnablementRefreshRequirementProvider.class);
|
||||
private static final Logger logger = LoggerFactory.getLogger(LinkedDeviceRefreshRequirementProvider.class);
|
||||
|
||||
private static final String ACCOUNT_UUID = AuthEnablementRefreshRequirementProvider.class.getName() + ".accountUuid";
|
||||
private static final String DEVICES_ENABLED = AuthEnablementRefreshRequirementProvider.class.getName() + ".devicesEnabled";
|
||||
private static final String ACCOUNT_UUID = LinkedDeviceRefreshRequirementProvider.class.getName() + ".accountUuid";
|
||||
private static final String LINKED_DEVICE_IDS = LinkedDeviceRefreshRequirementProvider.class.getName() + ".deviceIds";
|
||||
|
||||
public AuthEnablementRefreshRequirementProvider(final AccountsManager accountsManager) {
|
||||
public LinkedDeviceRefreshRequirementProvider(final AccountsManager accountsManager) {
|
||||
this.accountsManager = accountsManager;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void handleRequestFiltered(final RequestEvent requestEvent) {
|
||||
if (requestEvent.getUriInfo().getMatchedResourceMethod().getInvocable().getHandlingMethod().getAnnotation(ChangesDeviceEnabledState.class) != null) {
|
||||
// The authenticated principal, if any, will be available after filters have run.
|
||||
// Now that the account is known, capture a snapshot of `isEnabled` for the account's devices before carrying out
|
||||
// the request’s business logic.
|
||||
ContainerRequestUtil.getAuthenticatedAccount(requestEvent.getContainerRequest()).ifPresent(account ->
|
||||
setAccount(requestEvent.getContainerRequest(), account));
|
||||
if (requestEvent.getUriInfo().getMatchedResourceMethod().getInvocable().getHandlingMethod().getAnnotation(
|
||||
ChangesLinkedDevices.class) != null) {
|
||||
// The authenticated principal, if any, will be available after filters have run. Now that the account is known,
|
||||
// capture a snapshot of the account's linked devices before carrying out the request’s business logic.
|
||||
ContainerRequestUtil.getAuthenticatedAccount(requestEvent.getContainerRequest())
|
||||
.ifPresent(account -> setAccount(requestEvent.getContainerRequest(), account));
|
||||
}
|
||||
}
|
||||
|
||||
public static void setAccount(final ContainerRequest containerRequest, final Account account) {
|
||||
setAccount(containerRequest, ContainerRequestUtil.AccountInfo.fromAccount(account));
|
||||
}
|
||||
|
||||
private static void setAccount(final ContainerRequest containerRequest, final ContainerRequestUtil.AccountInfo info) {
|
||||
containerRequest.setProperty(ACCOUNT_UUID, info.accountId());
|
||||
containerRequest.setProperty(DEVICES_ENABLED, info.devicesEnabled());
|
||||
containerRequest.setProperty(LINKED_DEVICE_IDS, info.deviceIds());
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Pair<UUID, Byte>> handleRequestFinished(final RequestEvent requestEvent) {
|
||||
// Now that the request is finished, check whether `isEnabled` changed for any of the devices. If the value did
|
||||
// change or if a devices was added or removed, all devices must disconnect and reauthenticate.
|
||||
if (requestEvent.getContainerRequest().getProperty(DEVICES_ENABLED) != null) {
|
||||
// Now that the request is finished, check whether the set of linked devices has changed. If the value did change or
|
||||
// if a devices was added or removed, all devices must disconnect and reauthenticate.
|
||||
if (requestEvent.getContainerRequest().getProperty(LINKED_DEVICE_IDS) != null) {
|
||||
|
||||
@SuppressWarnings("unchecked") final Map<Byte, Boolean> initialDevicesEnabled =
|
||||
(Map<Byte, Boolean>) requestEvent.getContainerRequest().getProperty(DEVICES_ENABLED);
|
||||
@SuppressWarnings("unchecked") final Set<Byte> initialLinkedDeviceIds =
|
||||
(Set<Byte>) requestEvent.getContainerRequest().getProperty(LINKED_DEVICE_IDS);
|
||||
|
||||
return accountsManager.getByAccountIdentifier((UUID) requestEvent.getContainerRequest().getProperty(ACCOUNT_UUID))
|
||||
.map(ContainerRequestUtil.AccountInfo::fromAccount)
|
||||
.map(account -> {
|
||||
.map(accountInfo -> {
|
||||
final Set<Byte> deviceIdsToDisplace;
|
||||
final Map<Byte, Boolean> currentDevicesEnabled = account.devicesEnabled();
|
||||
final Set<Byte> currentLinkedDeviceIds = accountInfo.deviceIds();
|
||||
|
||||
if (!initialDevicesEnabled.equals(currentDevicesEnabled)) {
|
||||
deviceIdsToDisplace = new HashSet<>(initialDevicesEnabled.keySet());
|
||||
deviceIdsToDisplace.addAll(currentDevicesEnabled.keySet());
|
||||
if (!initialLinkedDeviceIds.equals(currentLinkedDeviceIds)) {
|
||||
deviceIdsToDisplace = new HashSet<>(initialLinkedDeviceIds);
|
||||
deviceIdsToDisplace.addAll(currentLinkedDeviceIds);
|
||||
} else {
|
||||
deviceIdsToDisplace = Collections.emptySet();
|
||||
}
|
||||
|
||||
return deviceIdsToDisplace.stream()
|
||||
.map(deviceId -> new Pair<>(account.accountId(), deviceId))
|
||||
.map(deviceId -> new Pair<>(accountInfo.accountId(), deviceId))
|
||||
.collect(Collectors.toList());
|
||||
}).orElseGet(() -> {
|
||||
logger.error("Request had account, but it is no longer present");
|
||||
@@ -18,6 +18,8 @@ import java.util.Optional;
|
||||
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
|
||||
public class OptionalAccess {
|
||||
|
||||
public static String ALL_DEVICES_SELECTOR = "*";
|
||||
|
||||
public static void verify(Optional<Account> requestAccount,
|
||||
Optional<Anonymous> accessKey,
|
||||
Optional<Account> targetAccount,
|
||||
@@ -26,12 +28,12 @@ public class OptionalAccess {
|
||||
try {
|
||||
verify(requestAccount, accessKey, targetAccount);
|
||||
|
||||
if (!deviceSelector.equals("*")) {
|
||||
if (!ALL_DEVICES_SELECTOR.equals(deviceSelector)) {
|
||||
byte deviceId = Byte.parseByte(deviceSelector);
|
||||
|
||||
Optional<Device> targetDevice = targetAccount.get().getDevice(deviceId);
|
||||
|
||||
if (targetDevice.isPresent() && targetDevice.get().isEnabled()) {
|
||||
if (targetDevice.isPresent()) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -48,11 +50,10 @@ public class OptionalAccess {
|
||||
|
||||
public static void verify(Optional<Account> requestAccount,
|
||||
Optional<Anonymous> accessKey,
|
||||
Optional<Account> targetAccount)
|
||||
{
|
||||
Optional<Account> targetAccount) {
|
||||
if (requestAccount.isPresent()) {
|
||||
// Authenticated requests are never unauthorized; if the target exists and is enabled, return OK, otherwise throw not-found.
|
||||
if (targetAccount.isPresent() && targetAccount.get().isEnabled()) {
|
||||
// Authenticated requests are never unauthorized; if the target exists, return OK, otherwise throw not-found.
|
||||
if (targetAccount.isPresent()) {
|
||||
return;
|
||||
} else {
|
||||
throw new NotFoundException();
|
||||
@@ -63,7 +64,7 @@ public class OptionalAccess {
|
||||
// has unrestricted unidentified access, callers need to supply a fake access key. Likewise, if
|
||||
// the target account does not exist, we *also* report unauthorized here (*not* not-found,
|
||||
// since that would provide a free exists check).
|
||||
if (accessKey.isEmpty() || !targetAccount.map(Account::isEnabled).orElse(false)) {
|
||||
if (accessKey.isEmpty() || targetAccount.isEmpty()) {
|
||||
throw new NotAuthorizedException(Response.Status.UNAUTHORIZED);
|
||||
}
|
||||
|
||||
|
||||
+1
-17
@@ -17,7 +17,6 @@ import java.util.UUID;
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import org.whispersystems.textsecuregcm.calls.routing.TurnServerOptions;
|
||||
import org.whispersystems.textsecuregcm.configuration.CloudflareTurnConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.TurnUriConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicTurnConfiguration;
|
||||
@@ -38,21 +37,10 @@ public class TurnTokenGenerator {
|
||||
|
||||
private static final String WithIpsProtocol = "01";
|
||||
|
||||
private final String cloudflareTurnUsername;
|
||||
private final String cloudflareTurnPassword;
|
||||
private final List<String> cloudflareTurnUrls;
|
||||
private final String cloudflareTurnHostname;
|
||||
|
||||
public TurnTokenGenerator(final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
|
||||
final byte[] turnSecret, final CloudflareTurnConfiguration cloudflareTurnConfiguration) {
|
||||
|
||||
final byte[] turnSecret) {
|
||||
this.dynamicConfigurationManager = dynamicConfigurationManager;
|
||||
this.turnSecret = turnSecret;
|
||||
|
||||
this.cloudflareTurnUsername = cloudflareTurnConfiguration.username().value();
|
||||
this.cloudflareTurnPassword = cloudflareTurnConfiguration.password().value();
|
||||
this.cloudflareTurnUrls = cloudflareTurnConfiguration.urls();
|
||||
this.cloudflareTurnHostname = cloudflareTurnConfiguration.hostname();
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
@@ -64,10 +52,6 @@ public class TurnTokenGenerator {
|
||||
return generateToken(options.hostname(), options.urlsWithIps(), options.urlsWithHostname());
|
||||
}
|
||||
|
||||
public TurnToken generateForCloudflareBeta() {
|
||||
return new TurnToken(cloudflareTurnUsername, cloudflareTurnPassword, cloudflareTurnUrls, null, cloudflareTurnHostname);
|
||||
}
|
||||
|
||||
private TurnToken generateToken(String hostname, List<String> urlsWithIps, List<String> urlsWithHostname) {
|
||||
try {
|
||||
final Mac mac = Mac.getInstance(ALGORITHM);
|
||||
|
||||
+1
-1
@@ -23,7 +23,7 @@ public class WebsocketRefreshApplicationEventListener implements ApplicationEven
|
||||
final ClientPresenceManager clientPresenceManager) {
|
||||
|
||||
this.websocketRefreshRequestEventListener = new WebsocketRefreshRequestEventListener(clientPresenceManager,
|
||||
new AuthEnablementRefreshRequirementProvider(accountsManager),
|
||||
new LinkedDeviceRefreshRequirementProvider(accountsManager),
|
||||
new PhoneNumberChangeRefreshRequirementProvider(accountsManager));
|
||||
}
|
||||
|
||||
|
||||
+10
-7
@@ -15,6 +15,7 @@ import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.stream.Stream;
|
||||
import javax.annotation.Nullable;
|
||||
import org.signal.libsignal.zkgroup.GenericServerSecretParams;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.VerificationFailedException;
|
||||
@@ -28,12 +29,12 @@ import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.RedeemedReceiptsManager;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
/**
|
||||
* Issues ZK backup auth credentials for authenticated accounts
|
||||
@@ -88,7 +89,7 @@ public class BackupAuthManager {
|
||||
* @throws RateLimitExceededException If too many backup-ids have been committed
|
||||
*/
|
||||
public CompletableFuture<Void> commitBackupId(final Account account,
|
||||
final BackupAuthCredentialRequest backupAuthCredentialRequest) throws RateLimitExceededException {
|
||||
final BackupAuthCredentialRequest backupAuthCredentialRequest) {
|
||||
if (configuredBackupLevel(account).isEmpty()) {
|
||||
throw Status.PERMISSION_DENIED.withDescription("Backups not allowed on account").asRuntimeException();
|
||||
}
|
||||
@@ -101,11 +102,13 @@ public class BackupAuthManager {
|
||||
return CompletableFuture.completedFuture(null);
|
||||
}
|
||||
|
||||
rateLimiters.forDescriptor(RateLimiters.For.SET_BACKUP_ID).validate(account.getUuid());
|
||||
|
||||
return this.accountsManager
|
||||
.updateAsync(account, acc -> acc.setBackupCredentialRequest(serializedRequest))
|
||||
.thenRun(Util.NOOP);
|
||||
return RateLimiter.adaptLegacyException(rateLimiters
|
||||
.forDescriptor(RateLimiters.For.SET_BACKUP_ID)
|
||||
.validateAsync(account.getUuid()))
|
||||
.thenCompose(ignored -> this.accountsManager
|
||||
.updateAsync(account, acc -> acc.setBackupCredentialRequest(serializedRequest))
|
||||
.thenRun(Util.NOOP))
|
||||
.toCompletableFuture();
|
||||
}
|
||||
|
||||
public record Credential(BackupAuthCredentialResponse credential, Instant redemptionTime) {}
|
||||
|
||||
+174
-123
@@ -14,13 +14,14 @@ import java.security.SecureRandom;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import java.util.function.Function;
|
||||
import org.signal.libsignal.protocol.ecc.Curve;
|
||||
import org.signal.libsignal.protocol.ecc.ECPublicKey;
|
||||
import org.signal.libsignal.zkgroup.GenericServerSecretParams;
|
||||
@@ -32,7 +33,6 @@ import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.attachments.AttachmentGenerator;
|
||||
import org.whispersystems.textsecuregcm.attachments.TusAttachmentGenerator;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedBackupUser;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
@@ -56,6 +56,9 @@ public class BackupManager {
|
||||
// How many cdn object deletion requests can be outstanding at a time per backup deletion operation
|
||||
private static final int DELETION_CONCURRENCY = 10;
|
||||
|
||||
// How many cdn object copy requests can be outstanding at a time per batch copy-to-backup operation
|
||||
private static final int COPY_CONCURRENCY = 10;
|
||||
|
||||
|
||||
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,
|
||||
@@ -148,19 +151,19 @@ public class BackupManager {
|
||||
.thenApply(result -> cdn3BackupCredentialGenerator.generateUpload(cdnMessageBackupName(backupUser)));
|
||||
}
|
||||
|
||||
public BackupUploadDescriptor createTemporaryAttachmentUploadDescriptor(final AuthenticatedBackupUser backupUser)
|
||||
throws RateLimitExceededException {
|
||||
public CompletableFuture<BackupUploadDescriptor> createTemporaryAttachmentUploadDescriptor(
|
||||
final AuthenticatedBackupUser backupUser) {
|
||||
checkBackupLevel(backupUser, BackupLevel.MEDIA);
|
||||
|
||||
RateLimiter.adaptLegacyException(() -> rateLimiters
|
||||
return RateLimiter.adaptLegacyException(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);
|
||||
return new BackupUploadDescriptor(3, attachmentKey, descriptor.headers(), descriptor.signedUploadLocation());
|
||||
.validateAsync(rateLimitKey(backupUser))).thenApply(ignored -> {
|
||||
final byte[] bytes = new byte[15];
|
||||
secureRandom.nextBytes(bytes);
|
||||
final String attachmentKey = Base64.getUrlEncoder().encodeToString(bytes);
|
||||
final AttachmentGenerator.Descriptor descriptor = tusAttachmentGenerator.generateAttachment(attachmentKey);
|
||||
return new BackupUploadDescriptor(3, attachmentKey, descriptor.headers(), descriptor.signedUploadLocation());
|
||||
}).toCompletableFuture();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -195,19 +198,96 @@ public class BackupManager {
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if there is enough capacity to store the requested amount of media
|
||||
* Copy an encrypted object to the backup cdn, adding a layer of encryption
|
||||
* <p>
|
||||
* Implementation notes: <p> This method guarantees that any object that gets successfully copied to the backup cdn
|
||||
* will also be deducted from the user's quota. </p>
|
||||
* <p>
|
||||
* However, the converse isn't true. It's possible we may charge the user for media they failed to copy. As a result,
|
||||
* the quota may be over reported. It should be recalculated before taking quota enforcement actions.
|
||||
*
|
||||
* @param backupUser an already ZK authenticated backup user
|
||||
* @param mediaLength the desired number of media bytes to store
|
||||
* @return true if mediaLength bytes can be stored
|
||||
* @return A Flux that emits the locations of the double-encrypted objects on the backup cdn, or includes an error
|
||||
* detailing why the object could not be copied.
|
||||
*/
|
||||
public CompletableFuture<Boolean> canStoreMedia(final AuthenticatedBackupUser backupUser, final long mediaLength) {
|
||||
public Flux<CopyResult> copyToBackup(final AuthenticatedBackupUser backupUser, List<CopyParameters> toCopy) {
|
||||
checkBackupLevel(backupUser, BackupLevel.MEDIA);
|
||||
|
||||
return Mono
|
||||
// Figure out how many objects we're allowed to copy, updating the quota usage for the amount we are allowed
|
||||
.fromFuture(enforceQuota(backupUser, toCopy))
|
||||
|
||||
// Copy the ones we have enough quota to hold
|
||||
.flatMapMany(quotaResult -> Flux.concat(
|
||||
|
||||
// These fit in our remaining quota, so perform the copy. If the copy fails, our estimated quota usage may not
|
||||
// be exact since we already updated our usage. We make a best-effort attempt to undo the usage update if we
|
||||
// know that the copied failed for sure though.
|
||||
Flux.fromIterable(quotaResult.requestsToCopy()).flatMapSequential(
|
||||
copyParams -> copyToBackup(backupUser, copyParams)
|
||||
.flatMap(copyResult -> switch (copyResult.outcome()) {
|
||||
case SUCCESS -> Mono.just(copyResult);
|
||||
case SOURCE_WRONG_LENGTH, SOURCE_NOT_FOUND, OUT_OF_QUOTA -> Mono
|
||||
.fromFuture(this.backupsDb.trackMedia(backupUser, -1, -copyParams.destinationObjectSize()))
|
||||
.thenReturn(copyResult);
|
||||
}),
|
||||
COPY_CONCURRENCY),
|
||||
|
||||
// There wasn't enough quota remaining to perform these copies
|
||||
Flux.fromIterable(quotaResult.requestsToReject())
|
||||
.map(arg -> new CopyResult(CopyResult.Outcome.OUT_OF_QUOTA, arg.destinationMediaId(), null))));
|
||||
}
|
||||
|
||||
private Mono<CopyResult> copyToBackup(final AuthenticatedBackupUser backupUser, final CopyParameters copyParameters) {
|
||||
return Mono.fromCompletionStage(() -> remoteStorageManager.copy(
|
||||
copyParameters.sourceCdn(), copyParameters.sourceKey(), copyParameters.sourceLength(),
|
||||
copyParameters.encryptionParameters(),
|
||||
cdnMediaPath(backupUser, copyParameters.destinationMediaId())))
|
||||
|
||||
// Successfully copied!
|
||||
.thenReturn(new CopyResult(
|
||||
CopyResult.Outcome.SUCCESS, copyParameters.destinationMediaId(), remoteStorageManager.cdnNumber()))
|
||||
|
||||
// Otherwise, squash per-item copy errors that don't fail the entire operation
|
||||
.onErrorResume(
|
||||
// If the error maps to an explicit result type
|
||||
throwable ->
|
||||
CopyResult.fromCopyError(throwable, copyParameters.destinationMediaId()).isPresent(),
|
||||
// return that result type instead of propagating the error
|
||||
throwable ->
|
||||
Mono.just(CopyResult.fromCopyError(throwable, copyParameters.destinationMediaId()).orElseThrow()));
|
||||
}
|
||||
|
||||
private record QuotaResult(List<CopyParameters> requestsToCopy, List<CopyParameters> requestsToReject) {}
|
||||
|
||||
/**
|
||||
* Determine which copy requests can be performed with the user's remaining quota and update the used quota. If a copy
|
||||
* request subsequently fails, the caller should attempt to restore the quota for the failed copy.
|
||||
*
|
||||
* @param backupUser The user quota to update
|
||||
* @param toCopy The proposed copy requests
|
||||
* @return QuotaResult indicating which requests fit into the remaining quota and which requests should be rejected
|
||||
* with {@link CopyResult.Outcome#OUT_OF_QUOTA}
|
||||
*/
|
||||
private CompletableFuture<QuotaResult> enforceQuota(
|
||||
final AuthenticatedBackupUser backupUser,
|
||||
final List<CopyParameters> toCopy) {
|
||||
final long totalBytesAdded = toCopy.stream()
|
||||
.mapToLong(copyParameters -> {
|
||||
if (copyParameters.sourceLength() > MAX_MEDIA_OBJECT_SIZE) {
|
||||
throw Status.INVALID_ARGUMENT
|
||||
.withDescription("Invalid sourceObject size")
|
||||
.asRuntimeException();
|
||||
}
|
||||
return copyParameters.destinationObjectSize();
|
||||
})
|
||||
.sum();
|
||||
|
||||
return backupsDb.getMediaUsage(backupUser)
|
||||
.thenComposeAsync(info -> {
|
||||
final boolean canStore = MAX_TOTAL_BACKUP_MEDIA_BYTES - info.usageInfo().bytesUsed() >= mediaLength;
|
||||
long remainingQuota = MAX_TOTAL_BACKUP_MEDIA_BYTES - info.usageInfo().bytesUsed();
|
||||
final boolean canStore = remainingQuota >= totalBytesAdded;
|
||||
if (canStore || info.lastRecalculationTime().isAfter(clock.instant().minus(MAX_QUOTA_STALENESS))) {
|
||||
return CompletableFuture.completedFuture(canStore);
|
||||
return CompletableFuture.completedFuture(remainingQuota);
|
||||
}
|
||||
|
||||
// The user is out of quota, and we have not recently recalculated the user's usage. Double check by doing a
|
||||
@@ -221,69 +301,46 @@ public class BackupManager {
|
||||
Metrics.counter(USAGE_RECALCULATION_COUNTER_NAME, "usageChanged", String.valueOf(usageChanged))
|
||||
.increment();
|
||||
})
|
||||
.thenApply(newUsage -> MAX_TOTAL_BACKUP_MEDIA_BYTES - newUsage.bytesUsed() >= mediaLength);
|
||||
.thenApply(newUsage -> MAX_TOTAL_BACKUP_MEDIA_BYTES - newUsage.bytesUsed());
|
||||
})
|
||||
.thenCompose(remainingQuota -> {
|
||||
// Figure out how many of the requested objects fit in the remaining quota
|
||||
final int index = indexWhereTotalExceeds(toCopy, CopyParameters::destinationObjectSize,
|
||||
remainingQuota);
|
||||
final QuotaResult result = new QuotaResult(toCopy.subList(0, index),
|
||||
toCopy.subList(index, toCopy.size()));
|
||||
if (index == 0) {
|
||||
// Skip the usage update if we're not able to write anything
|
||||
return CompletableFuture.completedFuture(result);
|
||||
}
|
||||
|
||||
// Update the usage
|
||||
final long quotaToConsume = result.requestsToCopy.stream()
|
||||
.mapToLong(CopyParameters::destinationObjectSize)
|
||||
.sum();
|
||||
return backupsDb.trackMedia(backupUser, index, quotaToConsume).thenApply(ignored -> result);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the largest index i such that sum(ts[0],...ts[i - 1]) <= max
|
||||
*/
|
||||
private static <T> int indexWhereTotalExceeds(List<T> ts, Function<T, Long> valueFunction, long max) {
|
||||
long sum = 0;
|
||||
for (int index = 0; index < ts.size(); index++) {
|
||||
sum += valueFunction.apply(ts.get(index));
|
||||
if (sum > max) {
|
||||
return index;
|
||||
}
|
||||
}
|
||||
return ts.size();
|
||||
}
|
||||
|
||||
|
||||
public record StorageDescriptor(int cdn, byte[] key) {}
|
||||
|
||||
public record StorageDescriptorWithLength(int cdn, byte[] key, long length) {}
|
||||
|
||||
/**
|
||||
* Copy an encrypted object to the backup cdn, adding a layer of encryption
|
||||
* <p>
|
||||
* Implementation notes: <p> This method guarantees that any object that gets successfully copied to the backup cdn
|
||||
* will also be deducted from the user's quota. </p>
|
||||
* <p>
|
||||
* However, the converse isn't true. It's possible we may charge the user for media they failed to copy. As a result,
|
||||
* the quota may be over reported and it should be recalculated before taking quota enforcement actions.
|
||||
*
|
||||
* @return A stage that completes successfully with location of the twice-encrypted object on the backup cdn. The
|
||||
* returned CompletionStage can be completed exceptionally with the following exceptions.
|
||||
* <ul>
|
||||
* <li> {@link InvalidLengthException} If the expectedSourceLength does not match the length of the sourceUri </li>
|
||||
* <li> {@link SourceObjectNotFoundException} If the no object at sourceUri is found </li>
|
||||
* <li> {@link java.io.IOException} If there was a generic IO issue </li>
|
||||
* </ul>
|
||||
*/
|
||||
public CompletableFuture<StorageDescriptor> copyToBackup(
|
||||
final AuthenticatedBackupUser backupUser,
|
||||
final int sourceCdn,
|
||||
final String sourceKey,
|
||||
final int sourceLength,
|
||||
final MediaEncryptionParameters encryptionParameters,
|
||||
final byte[] destinationMediaId) {
|
||||
checkBackupLevel(backupUser, BackupLevel.MEDIA);
|
||||
if (sourceLength > MAX_MEDIA_OBJECT_SIZE) {
|
||||
throw Status.INVALID_ARGUMENT
|
||||
.withDescription("Invalid sourceObject size")
|
||||
.asRuntimeException();
|
||||
}
|
||||
|
||||
final String destination = cdnMediaPath(backupUser, destinationMediaId);
|
||||
final int destinationLength = encryptionParameters.outputSize(sourceLength);
|
||||
return this.backupsDb
|
||||
// Write the ddb updates before actually updating backing storage
|
||||
.trackMedia(backupUser, 1, destinationLength)
|
||||
|
||||
// Actually copy the objects. If the copy fails, our estimated quota usage may not be exact
|
||||
.thenComposeAsync(ignored ->
|
||||
remoteStorageManager.copy(sourceCdn, sourceKey, sourceLength, encryptionParameters, destination))
|
||||
.exceptionallyCompose(throwable -> {
|
||||
final Throwable unwrapped = ExceptionUtils.unwrap(throwable);
|
||||
if (!(unwrapped instanceof SourceObjectNotFoundException) && !(unwrapped instanceof InvalidLengthException)) {
|
||||
throw ExceptionUtils.wrap(unwrapped);
|
||||
}
|
||||
// In cases where we know the copy fails without writing anything, we can try to restore the user's quota
|
||||
return this.backupsDb.trackMedia(backupUser, -1, -destinationLength).whenComplete((ignored, ignoredEx) -> {
|
||||
throw ExceptionUtils.wrap(unwrapped);
|
||||
});
|
||||
})
|
||||
// indicates where the backup was stored
|
||||
.thenApply(ignore -> new StorageDescriptor(remoteStorageManager.cdnNumber(), destinationMediaId));
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate credentials that can be used to read from the backup CDN
|
||||
*
|
||||
@@ -348,66 +405,60 @@ public class BackupManager {
|
||||
deletePrefix(backupUser.backupDir(), DELETION_CONCURRENCY))));
|
||||
}
|
||||
|
||||
private sealed interface Either permits DeleteSuccess, DeleteFailure {}
|
||||
|
||||
private record DeleteSuccess(long usage) implements Either {}
|
||||
|
||||
private record DeleteFailure(Throwable e) implements Either {}
|
||||
|
||||
public CompletableFuture<Void> delete(final AuthenticatedBackupUser backupUser,
|
||||
public Flux<StorageDescriptor> deleteMedia(final AuthenticatedBackupUser backupUser,
|
||||
final List<StorageDescriptor> storageDescriptors) {
|
||||
checkBackupLevel(backupUser, BackupLevel.MESSAGES);
|
||||
|
||||
// Check for a cdn we don't know how to process
|
||||
if (storageDescriptors.stream().anyMatch(sd -> sd.cdn() != remoteStorageManager.cdnNumber())) {
|
||||
throw Status.INVALID_ARGUMENT
|
||||
.withDescription("unsupported media cdn provided")
|
||||
.asRuntimeException();
|
||||
}
|
||||
|
||||
return Flux
|
||||
.fromIterable(storageDescriptors)
|
||||
return Flux.usingWhen(
|
||||
|
||||
// Issue deletes for all storage descriptors (proceeds with default flux concurrency)
|
||||
.flatMap(descriptor -> Mono.fromCompletionStage(
|
||||
remoteStorageManager
|
||||
.delete(cdnMediaPath(backupUser, descriptor.key))
|
||||
// Squash errors/success into a single type
|
||||
.handle((bytesDeleted, throwable) -> throwable != null
|
||||
? new DeleteFailure(throwable)
|
||||
: new DeleteSuccess(bytesDeleted))
|
||||
))
|
||||
// Gather usage updates into the UsageBatcher to apply during the cleanup operation
|
||||
Mono.just(new UsageBatcher()),
|
||||
|
||||
// Update backupsDb with the change in usage
|
||||
.collectList()
|
||||
.<Void>flatMap(eithers -> {
|
||||
// count up usage changes
|
||||
long totalBytesDeleted = 0;
|
||||
long totalCountDeleted = 0;
|
||||
final List<Throwable> toThrow = new ArrayList<>();
|
||||
for (Either either : eithers) {
|
||||
switch (either) {
|
||||
case DeleteFailure f:
|
||||
toThrow.add(f.e());
|
||||
break;
|
||||
case DeleteSuccess s when s.usage() > 0:
|
||||
totalBytesDeleted += s.usage();
|
||||
totalCountDeleted++;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
final Mono<Void> result = toThrow.isEmpty()
|
||||
? Mono.empty()
|
||||
: Mono.error(toThrow.stream().reduce((t1, t2) -> {
|
||||
t1.addSuppressed(t2);
|
||||
return t1;
|
||||
}).get());
|
||||
return Mono
|
||||
.fromCompletionStage(this.backupsDb.trackMedia(backupUser, -totalCountDeleted, -totalBytesDeleted))
|
||||
.then(result);
|
||||
})
|
||||
.toFuture();
|
||||
// Deletes the objects, returning their former location. Tracks bytes removed so the quota can be updated on
|
||||
// completion
|
||||
batcher -> Flux.fromIterable(storageDescriptors)
|
||||
.flatMapSequential(sd -> Mono
|
||||
// Delete the object
|
||||
.fromCompletionStage(remoteStorageManager.delete(cdnMediaPath(backupUser, sd.key())))
|
||||
// Track how much the remote storage manager indicated was deleted as part of the operation
|
||||
.doOnNext(deletedBytes -> batcher.update(-deletedBytes))
|
||||
.thenReturn(sd), DELETION_CONCURRENCY),
|
||||
|
||||
// On cleanup, update the quota using whatever updates were accumulated in the batcher
|
||||
batcher ->
|
||||
Mono.fromFuture(backupsDb.trackMedia(backupUser, batcher.countDelta.get(), batcher.usageDelta.get())));
|
||||
}
|
||||
|
||||
/**
|
||||
* Track pending media usage updates
|
||||
*/
|
||||
private static class UsageBatcher {
|
||||
|
||||
AtomicLong countDelta = new AtomicLong();
|
||||
AtomicLong usageDelta = new AtomicLong();
|
||||
|
||||
/**
|
||||
* Stage a usage update that will be applied later
|
||||
*
|
||||
* @param bytesDelta The amount of bytes that should be tracked as used (or if negative, freed). If the delta is
|
||||
* non-zero, the count will also be updated.
|
||||
*/
|
||||
void update(long bytesDelta) {
|
||||
if (bytesDelta < 0) {
|
||||
countDelta.decrementAndGet();
|
||||
} else if (bytesDelta > 0) {
|
||||
countDelta.incrementAndGet();
|
||||
}
|
||||
usageDelta.addAndGet(bytesDelta);
|
||||
}
|
||||
}
|
||||
|
||||
private static final ECPublicKey INVALID_PUBLIC_KEY = Curve.generateKeyPair().getPublicKey();
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.backup;
|
||||
|
||||
/**
|
||||
* Descriptor for a single copy-and-encrypt operation
|
||||
*
|
||||
* @param sourceCdn The cdn of the object to copy
|
||||
* @param sourceKey The mediaId within the cdn of the object to copy
|
||||
* @param sourceLength The length of the object to copy
|
||||
* @param encryptionParameters Encryption parameters to double encrypt the object
|
||||
* @param destinationMediaId The mediaId of the destination object
|
||||
*/
|
||||
public record CopyParameters(
|
||||
int sourceCdn,
|
||||
String sourceKey,
|
||||
int sourceLength,
|
||||
MediaEncryptionParameters encryptionParameters,
|
||||
byte[] destinationMediaId) {
|
||||
|
||||
/**
|
||||
* @return The size of the double-encrypted destination object after it is copied
|
||||
*/
|
||||
long destinationObjectSize() {
|
||||
return encryptionParameters().outputSize(sourceLength());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.backup;
|
||||
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
import java.util.Optional;
|
||||
|
||||
|
||||
/**
|
||||
* The result of a copy operation
|
||||
*
|
||||
* @param outcome Whether the copy was a success
|
||||
* @param mediaId The destination mediaId
|
||||
* @param cdn On success, the destination cdn
|
||||
*/
|
||||
public record CopyResult(Outcome outcome, byte[] mediaId, @Nullable Integer cdn) {
|
||||
|
||||
public enum Outcome {
|
||||
SUCCESS,
|
||||
SOURCE_NOT_FOUND,
|
||||
SOURCE_WRONG_LENGTH,
|
||||
OUT_OF_QUOTA
|
||||
}
|
||||
|
||||
/**
|
||||
* Map an exception returned by {@link RemoteStorageManager#copy} to CopyResult with the appropriate outcome.
|
||||
*
|
||||
* @param throwable result of a failed copy operation
|
||||
* @param key the copy destination mediaId
|
||||
* @return The appropriate CopyResult, or empty if the exception does not match to an Outcome.
|
||||
*/
|
||||
static Optional<CopyResult> fromCopyError(final Throwable throwable, final byte[] key) {
|
||||
final Throwable unwrapped = ExceptionUtils.unwrap(throwable);
|
||||
if (unwrapped instanceof SourceObjectNotFoundException) {
|
||||
return Optional.of(new CopyResult(Outcome.SOURCE_NOT_FOUND, key, null));
|
||||
} else if (unwrapped instanceof InvalidLengthException) {
|
||||
return Optional.of(new CopyResult(Outcome.SOURCE_WRONG_LENGTH, key, null));
|
||||
} else {
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
}
|
||||
+20
-2
@@ -11,7 +11,25 @@ import javax.validation.Valid;
|
||||
import javax.validation.constraints.NotBlank;
|
||||
import javax.validation.constraints.NotNull;
|
||||
|
||||
public record CloudflareTurnConfiguration(@NotNull SecretString username, @NotNull SecretString password,
|
||||
@Valid @NotNull List<@NotBlank String> urls, @NotBlank String hostname) {
|
||||
public record CloudflareTurnConfiguration(@NotNull SecretString apiToken,
|
||||
@NotBlank String endpoint,
|
||||
@NotBlank long ttl,
|
||||
@NotBlank List<String> urls,
|
||||
@NotBlank List<String> urlsWithIps,
|
||||
@NotNull @Valid CircuitBreakerConfiguration circuitBreaker,
|
||||
@NotNull @Valid RetryConfiguration retry,
|
||||
@NotBlank String hostname) {
|
||||
|
||||
public CloudflareTurnConfiguration {
|
||||
if (circuitBreaker == null) {
|
||||
// It’s a little counter-intuitive, but this compact constructor allows a default value
|
||||
// to be used when one isn’t specified (e.g. in YAML), allowing the field to still be
|
||||
// validated as @NotNull
|
||||
circuitBreaker = new CircuitBreakerConfiguration();
|
||||
}
|
||||
|
||||
if (retry == null) {
|
||||
retry = new RetryConfiguration();
|
||||
}
|
||||
}
|
||||
}
|
||||
+9
@@ -67,6 +67,7 @@ public class DynamoDbTables {
|
||||
private final TableWithExpiration registrationRecovery;
|
||||
private final Table remoteConfig;
|
||||
private final Table reportMessage;
|
||||
private final TableWithExpiration scheduledJobs;
|
||||
private final Table subscriptions;
|
||||
private final Table verificationSessions;
|
||||
|
||||
@@ -91,6 +92,7 @@ public class DynamoDbTables {
|
||||
@JsonProperty("registrationRecovery") final TableWithExpiration registrationRecovery,
|
||||
@JsonProperty("remoteConfig") final Table remoteConfig,
|
||||
@JsonProperty("reportMessage") final Table reportMessage,
|
||||
@JsonProperty("scheduledJobs") final TableWithExpiration scheduledJobs,
|
||||
@JsonProperty("subscriptions") final Table subscriptions,
|
||||
@JsonProperty("verificationSessions") final Table verificationSessions) {
|
||||
|
||||
@@ -114,6 +116,7 @@ public class DynamoDbTables {
|
||||
this.registrationRecovery = registrationRecovery;
|
||||
this.remoteConfig = remoteConfig;
|
||||
this.reportMessage = reportMessage;
|
||||
this.scheduledJobs = scheduledJobs;
|
||||
this.subscriptions = subscriptions;
|
||||
this.verificationSessions = verificationSessions;
|
||||
}
|
||||
@@ -238,6 +241,12 @@ public class DynamoDbTables {
|
||||
return reportMessage;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
public TableWithExpiration getScheduledJobs() {
|
||||
return scheduledJobs;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
public Table getSubscriptions() {
|
||||
|
||||
+8
@@ -67,6 +67,10 @@ public class DynamicConfiguration {
|
||||
@Valid
|
||||
DynamicMetricsConfiguration metricsConfiguration = new DynamicMetricsConfiguration(false);
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
DynamicMessagesConfiguration messagesConfiguration = new DynamicMessagesConfiguration();
|
||||
|
||||
public Optional<DynamicExperimentEnrollmentConfiguration> getExperimentEnrollmentConfiguration(
|
||||
final String experimentName) {
|
||||
return Optional.ofNullable(experiments.get(experimentName));
|
||||
@@ -121,4 +125,8 @@ public class DynamicConfiguration {
|
||||
return metricsConfiguration;
|
||||
}
|
||||
|
||||
public DynamicMessagesConfiguration getMessagesConfiguration() {
|
||||
return messagesConfiguration;
|
||||
}
|
||||
|
||||
}
|
||||
+8
-6
@@ -6,14 +6,13 @@
|
||||
package org.whispersystems.textsecuregcm.configuration.dynamic;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
|
||||
import javax.validation.Valid;
|
||||
import javax.validation.constraints.Max;
|
||||
import javax.validation.constraints.Min;
|
||||
import java.util.Collections;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import javax.validation.Valid;
|
||||
import javax.validation.constraints.Max;
|
||||
import javax.validation.constraints.Min;
|
||||
import javax.validation.constraints.NotNull;
|
||||
|
||||
public class DynamicExperimentEnrollmentConfiguration {
|
||||
|
||||
@@ -21,6 +20,7 @@ public class DynamicExperimentEnrollmentConfiguration {
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
@NotNull
|
||||
private Set<UUID> uuids = Collections.emptySet();
|
||||
|
||||
/**
|
||||
@@ -45,7 +45,9 @@ public class DynamicExperimentEnrollmentConfiguration {
|
||||
|
||||
}
|
||||
|
||||
private UuidSelector uuidSelector = new UuidSelector();
|
||||
@Valid
|
||||
@NotNull
|
||||
private final UuidSelector uuidSelector = new UuidSelector();
|
||||
|
||||
/**
|
||||
* If the UUID is not enrolled via {@link UuidSelector#uuids}, what is the percentage chance it should be enrolled.
|
||||
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration.dynamic;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import javax.validation.constraints.NotNull;
|
||||
|
||||
public record DynamicMessagesConfiguration(@NotNull List<DynamoKeyScheme> dynamoKeySchemes) {
|
||||
public enum DynamoKeyScheme {
|
||||
TRADITIONAL,
|
||||
LAZY_DELETION;
|
||||
}
|
||||
|
||||
public DynamicMessagesConfiguration() {
|
||||
this(List.of(DynamoKeyScheme.TRADITIONAL));
|
||||
}
|
||||
|
||||
public DynamoKeyScheme writeKeyScheme() {
|
||||
return dynamoKeySchemes().getLast();
|
||||
}
|
||||
}
|
||||
+2
-12
@@ -34,7 +34,6 @@ import javax.ws.rs.core.Response.Status;
|
||||
import org.signal.libsignal.usernames.BaseUsernameException;
|
||||
import org.whispersystems.textsecuregcm.auth.AccountAndAuthenticatedDeviceHolder;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
|
||||
import org.whispersystems.textsecuregcm.auth.ChangesDeviceEnabledState;
|
||||
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
|
||||
import org.whispersystems.textsecuregcm.auth.TurnToken;
|
||||
import org.whispersystems.textsecuregcm.auth.TurnTokenGenerator;
|
||||
@@ -109,7 +108,6 @@ public class AccountController {
|
||||
@Path("/gcm/")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@ChangesDeviceEnabledState
|
||||
public void setGcmRegistrationId(@Mutable @Auth AuthenticatedAccount auth,
|
||||
@NotNull @Valid GcmRegistrationId registrationId) {
|
||||
|
||||
@@ -130,7 +128,6 @@ public class AccountController {
|
||||
|
||||
@DELETE
|
||||
@Path("/gcm/")
|
||||
@ChangesDeviceEnabledState
|
||||
public void deleteGcmRegistrationId(@Mutable @Auth AuthenticatedAccount auth) {
|
||||
Account account = auth.getAccount();
|
||||
Device device = auth.getAuthenticatedDevice();
|
||||
@@ -146,19 +143,14 @@ public class AccountController {
|
||||
@Path("/apn/")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@ChangesDeviceEnabledState
|
||||
public void setApnRegistrationId(@Mutable @Auth AuthenticatedAccount auth,
|
||||
@NotNull @Valid ApnRegistrationId registrationId) {
|
||||
|
||||
final Account account = auth.getAccount();
|
||||
final Device device = auth.getAuthenticatedDevice();
|
||||
|
||||
if (Objects.equals(device.getApnId(), registrationId.apnRegistrationId()) &&
|
||||
Objects.equals(device.getVoipApnId(), registrationId.voipRegistrationId())) {
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// Unlike FCM tokens, we need current "last updated" timestamps for APNs tokens and so update device records
|
||||
// unconditionally
|
||||
accounts.updateDevice(account, device.getId(), d -> {
|
||||
d.setApnId(registrationId.apnRegistrationId());
|
||||
d.setVoipApnId(registrationId.voipRegistrationId());
|
||||
@@ -169,7 +161,6 @@ public class AccountController {
|
||||
|
||||
@DELETE
|
||||
@Path("/apn/")
|
||||
@ChangesDeviceEnabledState
|
||||
public void deleteApnRegistrationId(@Mutable @Auth AuthenticatedAccount auth) {
|
||||
Account account = auth.getAccount();
|
||||
Device device = auth.getAuthenticatedDevice();
|
||||
@@ -214,7 +205,6 @@ public class AccountController {
|
||||
@Path("/attributes/")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@ChangesDeviceEnabledState
|
||||
public void setAccountAttributes(
|
||||
@Mutable @Auth AuthenticatedAccount auth,
|
||||
@HeaderParam(HeaderUtils.X_SIGNAL_AGENT) String userAgent,
|
||||
|
||||
+54
-92
@@ -28,7 +28,7 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
import javax.annotation.Nullable;
|
||||
import java.util.stream.Stream;
|
||||
import javax.validation.Valid;
|
||||
import javax.validation.constraints.Max;
|
||||
import javax.validation.constraints.Min;
|
||||
@@ -54,22 +54,19 @@ import org.signal.libsignal.zkgroup.backups.BackupAuthCredentialPresentation;
|
||||
import org.signal.libsignal.zkgroup.backups.BackupAuthCredentialRequest;
|
||||
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialPresentation;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedBackupUser;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupAuthManager;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupManager;
|
||||
import org.whispersystems.textsecuregcm.backup.InvalidLengthException;
|
||||
import org.whispersystems.textsecuregcm.backup.CopyParameters;
|
||||
import org.whispersystems.textsecuregcm.backup.CopyResult;
|
||||
import org.whispersystems.textsecuregcm.backup.MediaEncryptionParameters;
|
||||
import org.whispersystems.textsecuregcm.backup.SourceObjectNotFoundException;
|
||||
import org.whispersystems.textsecuregcm.util.BackupAuthCredentialAdapter;
|
||||
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
|
||||
import org.whispersystems.textsecuregcm.util.ByteArrayBase64UrlAdapter;
|
||||
import org.whispersystems.textsecuregcm.util.ECPublicKeyAdapter;
|
||||
import org.whispersystems.textsecuregcm.util.ExactlySize;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
import org.whispersystems.websocket.auth.Mutable;
|
||||
import org.whispersystems.websocket.auth.ReadOnly;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
@Path("/v1/archives")
|
||||
@@ -124,7 +121,7 @@ public class ArchiveController {
|
||||
|
||||
public record RedeemBackupReceiptRequest(
|
||||
@Schema(description = "Presentation of a ZK receipt encoded in standard padded base64", implementation = String.class)
|
||||
@JsonDeserialize(using = RedeemBackupReceiptRequest.Deserializer.class)
|
||||
@JsonDeserialize(using = Deserializer.class)
|
||||
@NotNull
|
||||
ReceiptCredentialPresentation receiptCredentialPresentation) {
|
||||
|
||||
@@ -186,13 +183,13 @@ public class ArchiveController {
|
||||
description = """
|
||||
After setting a blinded backup-id with PUT /v1/archives/, this fetches credentials that can be used to perform
|
||||
operations against that backup-id. Clients may (and should) request up to 7 days of credentials at a time.
|
||||
|
||||
|
||||
The redemptionStart and redemptionEnd seconds must be UTC day aligned, and must not span more than 7 days.
|
||||
|
||||
|
||||
Each credential contains a receipt level which indicates the backup level the credential is good for. If the
|
||||
account has paid backup access that expires at some point in the provided redemption window, credentials with
|
||||
redemption times after the expiration may be on a lower backup level.
|
||||
|
||||
|
||||
Clients must validate the receipt level on the credential matches a known receipt level before using it.
|
||||
""")
|
||||
@ApiResponse(responseCode = "200", content = @Content(schema = @Schema(implementation = BackupAuthCredentialsResponse.class)))
|
||||
@@ -455,13 +452,7 @@ public class ArchiveController {
|
||||
throw new BadRequestException("must not use authenticated connection for anonymous operations");
|
||||
}
|
||||
return backupManager.authenticateBackupUser(presentation.presentation, signature.signature)
|
||||
.thenApply(backupUser -> {
|
||||
try {
|
||||
return backupManager.createTemporaryAttachmentUploadDescriptor(backupUser);
|
||||
} catch (RateLimitExceededException e) {
|
||||
throw ExceptionUtils.wrap(e);
|
||||
}
|
||||
})
|
||||
.thenCompose(backupUser -> backupManager.createTemporaryAttachmentUploadDescriptor(backupUser))
|
||||
.thenApply(result -> new UploadDescriptorResponse(
|
||||
result.cdn(),
|
||||
result.key(),
|
||||
@@ -509,7 +500,16 @@ public class ArchiveController {
|
||||
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
|
||||
@NotNull
|
||||
@ExactlySize(16)
|
||||
byte[] iv) {}
|
||||
byte[] iv) {
|
||||
|
||||
CopyParameters toCopyParameters() {
|
||||
return new CopyParameters(
|
||||
sourceAttachment.cdn, sourceAttachment.key,
|
||||
objectLength,
|
||||
new MediaEncryptionParameters(encryptionKey, hmacKey, iv),
|
||||
mediaId);
|
||||
}
|
||||
}
|
||||
|
||||
public record CopyMediaResponse(
|
||||
@Schema(description = "The backup cdn where this media object is stored")
|
||||
@@ -553,42 +553,20 @@ public class ArchiveController {
|
||||
throw new BadRequestException("must not use authenticated connection for anonymous operations");
|
||||
}
|
||||
|
||||
final AuthenticatedBackupUser backupUser = backupManager.authenticateBackupUser(
|
||||
presentation.presentation, signature.signature).join();
|
||||
|
||||
final boolean fits = backupManager.canStoreMedia(backupUser, copyMediaRequest.objectLength()).join();
|
||||
if (!fits) {
|
||||
throw new ClientErrorException("Media quota exhausted", Response.Status.REQUEST_ENTITY_TOO_LARGE);
|
||||
}
|
||||
return copyMediaImpl(backupUser, copyMediaRequest)
|
||||
.thenApply(result -> new CopyMediaResponse(result.cdn()))
|
||||
.exceptionally(e -> {
|
||||
final Throwable unwrapped = ExceptionUtils.unwrap(e);
|
||||
if (unwrapped instanceof SourceObjectNotFoundException) {
|
||||
throw new ClientErrorException("Source object not found " + unwrapped.getMessage(), Response.Status.GONE);
|
||||
} else if (unwrapped instanceof InvalidLengthException) {
|
||||
throw new BadRequestException("Invalid length " + unwrapped.getMessage());
|
||||
} else {
|
||||
throw ExceptionUtils.wrap(e);
|
||||
}
|
||||
});
|
||||
return Mono
|
||||
.fromFuture(backupManager.authenticateBackupUser(presentation.presentation, signature.signature))
|
||||
.flatMap(backupUser -> backupManager.copyToBackup(backupUser, List.of(copyMediaRequest.toCopyParameters()))
|
||||
.next()
|
||||
.map(copyResult -> switch (copyResult.outcome()) {
|
||||
case SUCCESS -> new CopyMediaResponse(copyResult.cdn());
|
||||
case SOURCE_WRONG_LENGTH -> throw new BadRequestException("Invalid length");
|
||||
case SOURCE_NOT_FOUND -> throw new ClientErrorException("Source object not found", Response.Status.GONE);
|
||||
case OUT_OF_QUOTA ->
|
||||
throw new ClientErrorException("Media quota exhausted", Response.Status.REQUEST_ENTITY_TOO_LARGE);
|
||||
}))
|
||||
.toFuture();
|
||||
}
|
||||
|
||||
private CompletionStage<BackupManager.StorageDescriptor> copyMediaImpl(final AuthenticatedBackupUser backupUser,
|
||||
final CopyMediaRequest copyMediaRequest) {
|
||||
return this.backupManager.copyToBackup(
|
||||
backupUser,
|
||||
copyMediaRequest.sourceAttachment.cdn,
|
||||
copyMediaRequest.sourceAttachment.key,
|
||||
copyMediaRequest.objectLength,
|
||||
new MediaEncryptionParameters(
|
||||
copyMediaRequest.encryptionKey,
|
||||
copyMediaRequest.hmacKey,
|
||||
copyMediaRequest.iv),
|
||||
copyMediaRequest.mediaId);
|
||||
}
|
||||
|
||||
|
||||
public record CopyMediaBatchRequest(
|
||||
@Schema(description = "A list of media objects to copy from the attachments CDN to the backup CDN")
|
||||
@NotNull
|
||||
@@ -606,6 +584,7 @@ public class ArchiveController {
|
||||
A 200 indicates the object was successfully copied.
|
||||
A 400 indicates an invalid argument in the request
|
||||
A 410 indicates that the source object was not found
|
||||
A 413 indicates that the media quota was exhausted
|
||||
""")
|
||||
int status,
|
||||
|
||||
@@ -620,7 +599,17 @@ public class ArchiveController {
|
||||
@JsonDeserialize(using = ByteArrayBase64UrlAdapter.Deserializing.class)
|
||||
@NotNull
|
||||
@ExactlySize(15)
|
||||
byte[] mediaId) {}
|
||||
byte[] mediaId) {
|
||||
|
||||
static Entry fromCopyResult(final CopyResult copyResult) {
|
||||
return switch (copyResult.outcome()) {
|
||||
case SUCCESS -> new Entry(200, null, copyResult.cdn(), copyResult.mediaId());
|
||||
case SOURCE_WRONG_LENGTH -> new Entry(400, "Invalid source length", null, copyResult.mediaId());
|
||||
case SOURCE_NOT_FOUND -> new Entry(410, "Source not found", null, copyResult.mediaId());
|
||||
case OUT_OF_QUOTA -> new Entry(413, "Media quota exhausted", null, copyResult.mediaId());
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@PUT
|
||||
@@ -661,39 +650,10 @@ public class ArchiveController {
|
||||
if (account.isPresent()) {
|
||||
throw new BadRequestException("must not use authenticated connection for anonymous operations");
|
||||
}
|
||||
|
||||
final AuthenticatedBackupUser backupUser = backupManager.authenticateBackupUser(
|
||||
presentation.presentation, signature.signature).join();
|
||||
|
||||
// If the entire batch won't fit in the user's remaining quota, reject the whole request.
|
||||
final long expectedStorage = copyMediaRequest.items().stream().mapToLong(CopyMediaRequest::objectLength).sum();
|
||||
final boolean fits = backupManager.canStoreMedia(backupUser, expectedStorage).join();
|
||||
if (!fits) {
|
||||
throw new ClientErrorException("Media quota exhausted", Response.Status.REQUEST_ENTITY_TOO_LARGE);
|
||||
}
|
||||
|
||||
return Flux.fromIterable(copyMediaRequest.items)
|
||||
// Operate sequentially, waiting for one copy to finish before starting the next one. At least right now,
|
||||
// copying concurrently will introduce contention over the metadata.
|
||||
.concatMap(request -> Mono
|
||||
.fromCompletionStage(copyMediaImpl(backupUser, request))
|
||||
.map(result -> new CopyMediaBatchResponse.Entry(200, null, result.cdn(), result.key()))
|
||||
.onErrorResume(throwable -> ExceptionUtils.unwrap(throwable) instanceof IOException, throwable -> {
|
||||
final Throwable unwrapped = ExceptionUtils.unwrap(throwable);
|
||||
|
||||
int status;
|
||||
String error;
|
||||
if (unwrapped instanceof SourceObjectNotFoundException) {
|
||||
status = 410;
|
||||
error = "Source object not found " + unwrapped.getMessage();
|
||||
} else if (unwrapped instanceof InvalidLengthException) {
|
||||
status = 400;
|
||||
error = "Invalid length " + unwrapped.getMessage();
|
||||
} else {
|
||||
throw ExceptionUtils.wrap(throwable);
|
||||
}
|
||||
return Mono.just(new CopyMediaBatchResponse.Entry(status, error, null, request.mediaId));
|
||||
}))
|
||||
final Stream<CopyParameters> copyParams = copyMediaRequest.items().stream().map(CopyMediaRequest::toCopyParameters);
|
||||
return Mono.fromFuture(backupManager.authenticateBackupUser(presentation.presentation, signature.signature))
|
||||
.flatMapMany(backupUser -> backupManager.copyToBackup(backupUser, copyParams.toList()))
|
||||
.map(CopyMediaBatchResponse.Entry::fromCopyResult)
|
||||
.collectList()
|
||||
.map(list -> Response.status(207).entity(new CopyMediaBatchResponse(list)).build())
|
||||
.toFuture();
|
||||
@@ -847,19 +807,21 @@ public class ArchiveController {
|
||||
throw new BadRequestException("must not use authenticated connection for anonymous operations");
|
||||
}
|
||||
|
||||
final List<BackupManager.StorageDescriptor> toDelete = deleteMedia.mediaToDelete().stream()
|
||||
.map(media -> new BackupManager.StorageDescriptor(media.cdn(), media.mediaId))
|
||||
.toList();
|
||||
|
||||
return backupManager
|
||||
.authenticateBackupUser(presentation.presentation, signature.signature)
|
||||
.thenCompose(authenticatedBackupUser -> backupManager.delete(authenticatedBackupUser,
|
||||
deleteMedia.mediaToDelete().stream()
|
||||
.map(media -> new BackupManager.StorageDescriptor(media.cdn(), media.mediaId))
|
||||
.toList()))
|
||||
.thenCompose(authenticatedBackupUser -> backupManager
|
||||
.deleteMedia(authenticatedBackupUser, toDelete)
|
||||
.then().toFuture())
|
||||
.thenApply(Util.ASYNC_EMPTY_RESPONSE);
|
||||
}
|
||||
|
||||
@DELETE
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Operation(summary = "Delete entire backup",
|
||||
description = """
|
||||
@Operation(summary = "Delete entire backup", description = """
|
||||
Delete all backup metadata, objects, and stored public key. To use backups again, a public key must be resupplied.
|
||||
""")
|
||||
@ApiResponse(responseCode = "204", description = "The backup has been successfully removed")
|
||||
|
||||
+2
@@ -31,6 +31,8 @@ import org.whispersystems.textsecuregcm.util.Conversions;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import org.whispersystems.websocket.auth.ReadOnly;
|
||||
|
||||
// To be removed when Android 7.12 reaches saturation, likely some time toward the end of October 2024
|
||||
@Deprecated(forRemoval = true)
|
||||
@Path("/v2/attachments")
|
||||
@Tag(name = "Attachments")
|
||||
public class AttachmentControllerV2 {
|
||||
|
||||
+2
@@ -25,6 +25,8 @@ import org.whispersystems.textsecuregcm.limits.RateLimiter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.websocket.auth.ReadOnly;
|
||||
|
||||
// To be removed when Desktop 7.17 reaches saturation, likely some time toward the end of October 2024
|
||||
@Deprecated(forRemoval = true)
|
||||
@Path("/v3/attachments")
|
||||
@Tag(name = "Attachments")
|
||||
public class AttachmentControllerV3 {
|
||||
|
||||
+8
-3
@@ -7,6 +7,7 @@ import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import java.io.IOException;
|
||||
import java.net.InetAddress;
|
||||
import java.net.UnknownHostException;
|
||||
import java.util.Optional;
|
||||
@@ -20,6 +21,7 @@ import javax.ws.rs.core.MediaType;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
|
||||
import org.whispersystems.textsecuregcm.auth.CloudflareTurnCredentialsManager;
|
||||
import org.whispersystems.textsecuregcm.auth.TurnToken;
|
||||
import org.whispersystems.textsecuregcm.auth.TurnTokenGenerator;
|
||||
import org.whispersystems.textsecuregcm.calls.routing.TurnCallRouter;
|
||||
@@ -40,17 +42,20 @@ public class CallRoutingController {
|
||||
private final TurnCallRouter turnCallRouter;
|
||||
private final TurnTokenGenerator tokenGenerator;
|
||||
private final ExperimentEnrollmentManager experimentEnrollmentManager;
|
||||
private final CloudflareTurnCredentialsManager cloudflareTurnCredentialsManager;
|
||||
|
||||
public CallRoutingController(
|
||||
final RateLimiters rateLimiters,
|
||||
final TurnCallRouter turnCallRouter,
|
||||
final TurnTokenGenerator tokenGenerator,
|
||||
final ExperimentEnrollmentManager experimentEnrollmentManager
|
||||
final ExperimentEnrollmentManager experimentEnrollmentManager,
|
||||
final CloudflareTurnCredentialsManager cloudflareTurnCredentialsManager
|
||||
) {
|
||||
this.rateLimiters = rateLimiters;
|
||||
this.turnCallRouter = turnCallRouter;
|
||||
this.tokenGenerator = tokenGenerator;
|
||||
this.experimentEnrollmentManager = experimentEnrollmentManager;
|
||||
this.cloudflareTurnCredentialsManager = cloudflareTurnCredentialsManager;
|
||||
}
|
||||
|
||||
@GET
|
||||
@@ -70,12 +75,12 @@ public class CallRoutingController {
|
||||
public TurnToken getCallingRelays(
|
||||
final @ReadOnly @Auth AuthenticatedAccount auth,
|
||||
@Context ContainerRequestContext requestContext
|
||||
) throws RateLimitExceededException {
|
||||
) throws RateLimitExceededException, IOException {
|
||||
UUID aci = auth.getAccount().getUuid();
|
||||
rateLimiters.getCallEndpointLimiter().validate(aci);
|
||||
|
||||
if (experimentEnrollmentManager.isEnrolled(aci, "cloudflareTurn")) {
|
||||
return tokenGenerator.generateForCloudflareBeta();
|
||||
return cloudflareTurnCredentialsManager.retrieveFromCloudflare();
|
||||
}
|
||||
|
||||
Optional<InetAddress> address = Optional.empty();
|
||||
|
||||
+12
-5
@@ -46,10 +46,10 @@ import javax.ws.rs.core.Context;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
import org.glassfish.jersey.server.ContainerRequest;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthEnablementRefreshRequirementProvider;
|
||||
import org.whispersystems.textsecuregcm.auth.LinkedDeviceRefreshRequirementProvider;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
|
||||
import org.whispersystems.textsecuregcm.auth.BasicAuthorizationHeader;
|
||||
import org.whispersystems.textsecuregcm.auth.ChangesDeviceEnabledState;
|
||||
import org.whispersystems.textsecuregcm.auth.ChangesLinkedDevices;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
|
||||
import org.whispersystems.textsecuregcm.entities.DeviceActivationRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.DeviceInfo;
|
||||
@@ -132,7 +132,7 @@ public class DeviceController {
|
||||
@DELETE
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/{device_id}")
|
||||
@ChangesDeviceEnabledState
|
||||
@ChangesLinkedDevices
|
||||
public void removeDevice(@Mutable @Auth AuthenticatedAccount auth, @PathParam("device_id") byte deviceId) {
|
||||
if (auth.getAuthenticatedDevice().getId() != Device.PRIMARY_ID) {
|
||||
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
|
||||
@@ -176,13 +176,14 @@ public class DeviceController {
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Path("/link")
|
||||
@ChangesDeviceEnabledState
|
||||
@ChangesLinkedDevices
|
||||
@Operation(summary = "Link a device to an account",
|
||||
description = """
|
||||
Links a device to an account identified by a given phone number.
|
||||
""")
|
||||
@ApiResponse(responseCode = "200", description = "The new device was linked to the calling account", useReturnTypeSchema = true)
|
||||
@ApiResponse(responseCode = "403", description = "The given account was not found or the given verification code was incorrect")
|
||||
@ApiResponse(responseCode = "409", description = "The new device is missing a capability supported by all other devices on the account")
|
||||
@ApiResponse(responseCode = "411", description = "The given account already has its maximum number of linked devices")
|
||||
@ApiResponse(responseCode = "422", description = "The request did not pass validation")
|
||||
@ApiResponse(responseCode = "429", description = "Too many attempts", headers = @Header(
|
||||
@@ -220,7 +221,7 @@ public class DeviceController {
|
||||
// Normally, the "do we need to refresh somebody's websockets" listener can do this on its own. In this case,
|
||||
// we're not using the conventional authentication system, and so we need to give it a hint so it knows who the
|
||||
// active user is and what their device states look like.
|
||||
AuthEnablementRefreshRequirementProvider.setAccount(containerRequest, account);
|
||||
LinkedDeviceRefreshRequirementProvider.setAccount(containerRequest, account);
|
||||
|
||||
final int maxDeviceLimit = maxDeviceConfiguration.getOrDefault(account.getNumber(), MAX_DEVICES);
|
||||
|
||||
@@ -232,6 +233,8 @@ public class DeviceController {
|
||||
|
||||
if (capabilities == null) {
|
||||
throw new WebApplicationException(Response.status(422, "Missing device capabilities").build());
|
||||
} else if (isCapabilityDowngrade(account, capabilities)) {
|
||||
throw new WebApplicationException(Response.status(409).build());
|
||||
}
|
||||
|
||||
final String signalAgent;
|
||||
@@ -387,6 +390,10 @@ public class DeviceController {
|
||||
return Optional.of(aci);
|
||||
}
|
||||
|
||||
private static boolean isCapabilityDowngrade(Account account, DeviceCapabilities capabilities) {
|
||||
return account.isDeleteSyncSupported() && !capabilities.deleteSync();
|
||||
}
|
||||
|
||||
private static String getUsedTokenKey(final String token) {
|
||||
return "usedToken::" + token;
|
||||
}
|
||||
|
||||
+3
-32
@@ -313,7 +313,7 @@ public class KeysController {
|
||||
@ApiResponse(responseCode = "200", description = "Indicates at least one prekey was available for at least one requested device.", useReturnTypeSchema = true)
|
||||
@ApiResponse(responseCode = "400", description = "A group send endorsement and other authorization (account authentication or unidentified-access key) were both provided.")
|
||||
@ApiResponse(responseCode = "401", description = "Account authentication check failed and unidentified-access key or group send endorsement token was not supplied or invalid.")
|
||||
@ApiResponse(responseCode = "404", description = "Requested identity or device does not exist, is not active, or has no available prekeys.")
|
||||
@ApiResponse(responseCode = "404", description = "Requested identity or device does not exist or device has no available prekeys.")
|
||||
@ApiResponse(responseCode = "429", description = "Rate limit exceeded.", headers = @Header(
|
||||
name = "Retry-After",
|
||||
description = "If present, a positive integer indicating the number of seconds before a subsequent attempt could succeed"))
|
||||
@@ -409,42 +409,13 @@ public class KeysController {
|
||||
return new PreKeyResponse(identityKey, responseItems);
|
||||
}
|
||||
|
||||
@PUT
|
||||
@Path("/signed")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Operation(summary = "Upload a new signed prekey",
|
||||
description = """
|
||||
Upload a new signed elliptic-curve prekey for this device. Deprecated; use PUT /v2/keys instead.
|
||||
""")
|
||||
@ApiResponse(responseCode = "200", description = "Indicates that new prekey was successfully stored.")
|
||||
@ApiResponse(responseCode = "401", description = "Account authentication check failed.")
|
||||
@ApiResponse(responseCode = "422", description = "Invalid request format.")
|
||||
// TODO Remove this endpoint on or after 2024-05-24
|
||||
@Deprecated(forRemoval = true)
|
||||
public CompletableFuture<Response> setSignedKey(
|
||||
@ReadOnly @Auth final AuthenticatedAccount auth,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) @Nullable final String userAgent,
|
||||
@Valid final ECSignedPreKey signedPreKey,
|
||||
@QueryParam("identity") @DefaultValue("aci") final IdentityType identityType) {
|
||||
|
||||
final UUID identifier = auth.getAccount().getIdentifier(identityType);
|
||||
final byte deviceId = auth.getAuthenticatedDevice().getId();
|
||||
|
||||
if (!PreKeySignatureValidator.validatePreKeySignatures(auth.getAccount().getIdentityKey(identityType), List.of(signedPreKey), userAgent, "set-signed-pre-key")) {
|
||||
throw new WebApplicationException("Invalid signature", 422);
|
||||
}
|
||||
|
||||
return keysManager.storeEcSignedPreKeys(identifier, deviceId, signedPreKey)
|
||||
.thenApply(Util.ASYNC_EMPTY_RESPONSE);
|
||||
}
|
||||
|
||||
private List<Device> parseDeviceId(String deviceId, Account account) {
|
||||
if (deviceId.equals("*")) {
|
||||
return account.getDevices().stream().filter(Device::isEnabled).toList();
|
||||
return account.getDevices();
|
||||
}
|
||||
try {
|
||||
byte id = Byte.parseByte(deviceId);
|
||||
return account.getDevice(id).filter(Device::isEnabled).map(List::of).orElse(List.of());
|
||||
return account.getDevice(id).map(List::of).orElse(List.of());
|
||||
} catch (NumberFormatException e) {
|
||||
throw new WebApplicationException(Response.status(422).build());
|
||||
}
|
||||
|
||||
+96
-92
@@ -8,13 +8,12 @@ import static com.codahale.metrics.MetricRegistry.name;
|
||||
|
||||
import com.codahale.metrics.annotation.Timed;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.common.collect.Iterables;
|
||||
import com.google.common.collect.Lists;
|
||||
import com.google.common.net.HttpHeaders;
|
||||
import com.google.protobuf.ByteString;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.dropwizard.util.DataSize;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.DistributionSummary;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
@@ -113,7 +112,6 @@ import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.providers.MultiRecipientMessageProvider;
|
||||
import org.whispersystems.textsecuregcm.push.MessageSender;
|
||||
import org.whispersystems.textsecuregcm.push.NotPushRegisteredException;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
|
||||
import org.whispersystems.textsecuregcm.push.ReceiptSender;
|
||||
import org.whispersystems.textsecuregcm.spam.ReportSpamTokenProvider;
|
||||
@@ -176,12 +174,11 @@ public class MessageController {
|
||||
|
||||
private static final String REJECT_OVERSIZE_MESSAGE_COUNTER = name(MessageController.class, "rejectOversizeMessage");
|
||||
private static final String SENT_MESSAGE_COUNTER_NAME = name(MessageController.class, "sentMessages");
|
||||
private static final String CONTENT_SIZE_DISTRIBUTION_NAME = name(MessageController.class, "messageContentSize");
|
||||
private static final String CONTENT_SIZE_DISTRIBUTION_NAME = MetricsUtil.name(MessageController.class, "messageContentSize");
|
||||
private static final String OUTGOING_MESSAGE_LIST_SIZE_BYTES_DISTRIBUTION_NAME = name(MessageController.class, "outgoingMessageListSizeBytes");
|
||||
private static final String RATE_LIMITED_MESSAGE_COUNTER_NAME = name(MessageController.class, "rateLimitedMessage");
|
||||
|
||||
private static final String REJECT_INVALID_ENVELOPE_TYPE = name(MessageController.class, "rejectInvalidEnvelopeType");
|
||||
private static final String UNEXPECTED_MISSING_USER_COUNTER_NAME = name(MessageController.class, "unexpectedMissingDestinationForMultiRecipientMessage");
|
||||
private static final Timer SEND_MESSAGE_LATENCY_TIMER =
|
||||
Timer.builder(MetricsUtil.name(MessageController.class, "sendMessageLatency"))
|
||||
.publishPercentileHistogram(true)
|
||||
@@ -189,6 +186,7 @@ public class MessageController {
|
||||
|
||||
private static final String EPHEMERAL_TAG_NAME = "ephemeral";
|
||||
private static final String SENDER_TYPE_TAG_NAME = "senderType";
|
||||
private static final String AUTH_TYPE_TAG_NAME = "authType";
|
||||
private static final String SENDER_COUNTRY_TAG_NAME = "senderCountry";
|
||||
private static final String RATE_LIMIT_REASON_TAG_NAME = "rateLimitReason";
|
||||
private static final String ENVELOPE_TYPE_TAG_NAME = "envelopeType";
|
||||
@@ -198,6 +196,10 @@ public class MessageController {
|
||||
private static final String SENDER_TYPE_UNIDENTIFIED = "unidentified";
|
||||
private static final String SENDER_TYPE_SELF = "self";
|
||||
|
||||
private static final String AUTH_TYPE_IDENTIFIED = "identified";
|
||||
private static final String AUTH_TYPE_ACCESS_KEY = "accessKey";
|
||||
private static final String AUTH_TYPE_GROUP_SEND_TOKEN = "groupSendToken";
|
||||
|
||||
@VisibleForTesting
|
||||
static final long MAX_MESSAGE_SIZE = DataSize.kibibytes(256).toBytes();
|
||||
|
||||
@@ -330,7 +332,7 @@ public class MessageController {
|
||||
|
||||
final Optional<byte[]> spamReportToken = switch (senderType) {
|
||||
case SENDER_TYPE_IDENTIFIED ->
|
||||
reportSpamTokenProvider.makeReportSpamToken(context, source.get().getAccount(), destination);
|
||||
reportSpamTokenProvider.makeReportSpamToken(context, source.get(), destination);
|
||||
default -> Optional.empty();
|
||||
};
|
||||
|
||||
@@ -343,7 +345,7 @@ public class MessageController {
|
||||
contentLength += message.content().length();
|
||||
}
|
||||
|
||||
validateContentLength(contentLength, userAgent);
|
||||
validateContentLength(contentLength, false, userAgent);
|
||||
validateEnvelopeType(message.type(), userAgent);
|
||||
|
||||
totalContentLength += contentLength;
|
||||
@@ -370,7 +372,7 @@ public class MessageController {
|
||||
OptionalAccess.verify(source.map(AuthenticatedAccount::getAccount), accessKey, destination);
|
||||
}
|
||||
|
||||
boolean needsSync = !isSyncMessage && source.isPresent() && source.get().getAccount().hasEnabledLinkedDevice();
|
||||
boolean needsSync = !isSyncMessage && source.isPresent() && source.get().getAccount().getDevices().size() > 1;
|
||||
|
||||
// We return 200 when stories are sent to a non-existent account. Since story sends bypass OptionalAccess.verify
|
||||
// we leak information about whether a destination UUID exists if we return any other code (e.g. 404) from
|
||||
@@ -409,9 +411,19 @@ public class MessageController {
|
||||
IncomingMessage::destinationRegistrationId,
|
||||
destination.get().getPhoneNumberIdentifier().equals(destinationIdentifier.uuid()));
|
||||
|
||||
final String authType;
|
||||
if (SENDER_TYPE_IDENTIFIED.equals(senderType)) {
|
||||
authType = AUTH_TYPE_IDENTIFIED;
|
||||
} else if (groupSendToken != null) {
|
||||
authType = AUTH_TYPE_GROUP_SEND_TOKEN;
|
||||
} else {
|
||||
authType = AUTH_TYPE_ACCESS_KEY;
|
||||
}
|
||||
|
||||
final List<Tag> tags = List.of(UserAgentTagUtil.getPlatformTag(userAgent),
|
||||
Tag.of(EPHEMERAL_TAG_NAME, String.valueOf(messages.online())),
|
||||
Tag.of(SENDER_TYPE_TAG_NAME, senderType),
|
||||
Tag.of(AUTH_TYPE_TAG_NAME, authType),
|
||||
Tag.of(IDENTITY_TYPE_TAG_NAME, destinationIdentifier.identityType().name()));
|
||||
|
||||
for (IncomingMessage incomingMessage : messages.messages()) {
|
||||
@@ -435,8 +447,6 @@ public class MessageController {
|
||||
}
|
||||
|
||||
return Response.ok(new SendMessageResponse(needsSync)).build();
|
||||
} catch (NoSuchUserException e) {
|
||||
throw new WebApplicationException(Response.status(404).build());
|
||||
} catch (MismatchedDevicesException e) {
|
||||
throw new WebApplicationException(Response.status(409)
|
||||
.type(MediaType.APPLICATION_JSON_TYPE)
|
||||
@@ -628,42 +638,38 @@ public class MessageController {
|
||||
.build();
|
||||
}
|
||||
|
||||
List<ServiceIdentifier> uuids404 = Collections.synchronizedList(new ArrayList<>());
|
||||
|
||||
try {
|
||||
CompletableFuture.allOf(
|
||||
recipients.values().stream()
|
||||
.flatMap(recipientData -> {
|
||||
final Counter sentMessageCounter = Metrics.counter(SENT_MESSAGE_COUNTER_NAME, Tags.of(
|
||||
UserAgentTagUtil.getPlatformTag(userAgent),
|
||||
Tag.of(EPHEMERAL_TAG_NAME, String.valueOf(online)),
|
||||
Tag.of(SENDER_TYPE_TAG_NAME, SENDER_TYPE_UNIDENTIFIED),
|
||||
Tag.of(IDENTITY_TYPE_TAG_NAME, recipientData.serviceIdentifier().identityType().name())));
|
||||
recipients.values().stream()
|
||||
.flatMap(recipientData -> {
|
||||
final Counter sentMessageCounter = Metrics.counter(SENT_MESSAGE_COUNTER_NAME, Tags.of(
|
||||
UserAgentTagUtil.getPlatformTag(userAgent),
|
||||
Tag.of(EPHEMERAL_TAG_NAME, String.valueOf(online)),
|
||||
Tag.of(SENDER_TYPE_TAG_NAME, SENDER_TYPE_UNIDENTIFIED),
|
||||
Tag.of(AUTH_TYPE_TAG_NAME,
|
||||
groupSendToken != null ? AUTH_TYPE_GROUP_SEND_TOKEN : AUTH_TYPE_ACCESS_KEY),
|
||||
Tag.of(IDENTITY_TYPE_TAG_NAME, recipientData.serviceIdentifier().identityType().name())));
|
||||
|
||||
return recipientData.deviceIdToRegistrationId().keySet().stream().map(
|
||||
deviceId ->CompletableFuture.runAsync(
|
||||
() -> {
|
||||
final Account destinationAccount = recipientData.account();
|
||||
final byte[] payload = multiRecipientMessage.messageForRecipient(recipientData.recipient());
|
||||
validateContentLength(multiRecipientMessage.messageSizeForRecipient(recipientData.recipient()), true, userAgent);
|
||||
|
||||
return recipientData.deviceIdToRegistrationId().keySet().stream().map(
|
||||
deviceId -> CompletableFuture.runAsync(
|
||||
() -> {
|
||||
final Account destinationAccount = recipientData.account();
|
||||
final byte[] payload = multiRecipientMessage.messageForRecipient(recipientData.recipient());
|
||||
|
||||
// we asserted this must exist in validateCompleteDeviceList
|
||||
final Device destinationDevice = destinationAccount.getDevice(deviceId).orElseThrow();
|
||||
|
||||
// we asserted this must exist in validateCompleteDeviceList
|
||||
final Device destinationDevice = destinationAccount.getDevice(deviceId).orElseThrow();
|
||||
try {
|
||||
sentMessageCounter.increment();
|
||||
sendCommonPayloadMessage(
|
||||
destinationAccount, destinationDevice, recipientData.serviceIdentifier(), timestamp, online,
|
||||
destinationAccount, destinationDevice, recipientData.serviceIdentifier(), timestamp,
|
||||
online,
|
||||
isStory, isUrgent, payload);
|
||||
} catch (NoSuchUserException e) {
|
||||
// this should never happen, because we already asserted the device is present and enabled
|
||||
Metrics.counter(
|
||||
UNEXPECTED_MISSING_USER_COUNTER_NAME,
|
||||
Tags.of("isPrimary", String.valueOf(destinationDevice.isPrimary()))).increment();
|
||||
uuids404.add(recipientData.serviceIdentifier());
|
||||
}
|
||||
},
|
||||
multiRecipientMessageExecutor));
|
||||
})
|
||||
.toArray(CompletableFuture[]::new))
|
||||
},
|
||||
multiRecipientMessageExecutor));
|
||||
})
|
||||
.toArray(CompletableFuture[]::new))
|
||||
.get();
|
||||
} catch (InterruptedException e) {
|
||||
logger.error("interrupted while delivering multi-recipient messages", e);
|
||||
@@ -675,7 +681,7 @@ public class MessageController {
|
||||
logger.error("partial failure while delivering multi-recipient messages", e.getCause());
|
||||
return Response.serverError().entity("failure during delivery").build();
|
||||
}
|
||||
return Response.ok(new SendMultiRecipientMessageResponse(uuids404)).build();
|
||||
return Response.ok(new SendMultiRecipientMessageResponse(Collections.emptyList())).build();
|
||||
}
|
||||
|
||||
private void checkGroupSendToken(
|
||||
@@ -724,7 +730,7 @@ public class MessageController {
|
||||
|
||||
return messagesManager.getMessagesForDevice(
|
||||
auth.getAccount().getUuid(),
|
||||
auth.getAuthenticatedDevice().getId(),
|
||||
auth.getAuthenticatedDevice(),
|
||||
false)
|
||||
.map(messagesAndHasMore -> {
|
||||
Stream<Envelope> envelopes = messagesAndHasMore.first().stream();
|
||||
@@ -736,7 +742,11 @@ public class MessageController {
|
||||
.map(OutgoingMessageEntity::fromEnvelope)
|
||||
.peek(outgoingMessageEntity -> {
|
||||
messageMetrics.measureAccountOutgoingMessageUuidMismatches(auth.getAccount(), outgoingMessageEntity);
|
||||
messageMetrics.measureOutgoingMessageLatency(outgoingMessageEntity.serverTimestamp(), "rest", userAgent, clientReleaseManager);
|
||||
messageMetrics.measureOutgoingMessageLatency(outgoingMessageEntity.serverTimestamp(),
|
||||
"rest",
|
||||
auth.getAuthenticatedDevice().isPrimary(),
|
||||
userAgent,
|
||||
clientReleaseManager);
|
||||
})
|
||||
.collect(Collectors.toList()),
|
||||
messagesAndHasMore.second());
|
||||
@@ -768,13 +778,13 @@ public class MessageController {
|
||||
public CompletableFuture<Response> removePendingMessage(@ReadOnly @Auth AuthenticatedAccount auth, @PathParam("uuid") UUID uuid) {
|
||||
return messagesManager.delete(
|
||||
auth.getAccount().getUuid(),
|
||||
auth.getAuthenticatedDevice().getId(),
|
||||
auth.getAuthenticatedDevice(),
|
||||
uuid,
|
||||
null)
|
||||
.thenAccept(maybeDeletedMessage -> {
|
||||
maybeDeletedMessage.ifPresent(deletedMessage -> {
|
||||
|
||||
WebSocketConnection.recordMessageDeliveryDuration(deletedMessage.getTimestamp(),
|
||||
WebSocketConnection.recordMessageDeliveryDuration(deletedMessage.getServerTimestamp(),
|
||||
auth.getAuthenticatedDevice());
|
||||
|
||||
if (deletedMessage.hasSourceUuid() && deletedMessage.getType() != Type.SERVER_DELIVERY_RECEIPT) {
|
||||
@@ -856,32 +866,27 @@ public class MessageController {
|
||||
boolean urgent,
|
||||
IncomingMessage incomingMessage,
|
||||
String userAgentString,
|
||||
Optional<byte[]> spamReportToken)
|
||||
throws NoSuchUserException {
|
||||
Optional<byte[]> spamReportToken) {
|
||||
|
||||
final Envelope envelope;
|
||||
|
||||
try {
|
||||
final Envelope envelope;
|
||||
|
||||
try {
|
||||
Account sourceAccount = source.map(AuthenticatedAccount::getAccount).orElse(null);
|
||||
Byte sourceDeviceId = source.map(account -> account.getAuthenticatedDevice().getId()).orElse(null);
|
||||
envelope = incomingMessage.toEnvelope(
|
||||
destinationIdentifier,
|
||||
sourceAccount,
|
||||
sourceDeviceId,
|
||||
timestamp == 0 ? System.currentTimeMillis() : timestamp,
|
||||
story,
|
||||
urgent,
|
||||
spamReportToken.orElse(null));
|
||||
} catch (final IllegalArgumentException e) {
|
||||
logger.warn("Received bad envelope type {} from {}", incomingMessage.type(), userAgentString);
|
||||
throw new BadRequestException(e);
|
||||
}
|
||||
|
||||
messageSender.sendMessage(destinationAccount, destinationDevice, envelope, online);
|
||||
} catch (NotPushRegisteredException e) {
|
||||
if (destinationDevice.isPrimary()) throw new NoSuchUserException(e);
|
||||
else logger.debug("Not registered", e);
|
||||
final Account sourceAccount = source.map(AuthenticatedAccount::getAccount).orElse(null);
|
||||
final Byte sourceDeviceId = source.map(account -> account.getAuthenticatedDevice().getId()).orElse(null);
|
||||
envelope = incomingMessage.toEnvelope(
|
||||
destinationIdentifier,
|
||||
sourceAccount,
|
||||
sourceDeviceId,
|
||||
timestamp == 0 ? System.currentTimeMillis() : timestamp,
|
||||
story,
|
||||
urgent,
|
||||
spamReportToken.orElse(null));
|
||||
} catch (final IllegalArgumentException e) {
|
||||
logger.warn("Received bad envelope type {} from {}", incomingMessage.type(), userAgentString);
|
||||
throw new BadRequestException(e);
|
||||
}
|
||||
|
||||
messageSender.sendMessage(destinationAccount, destinationDevice, envelope, online);
|
||||
}
|
||||
|
||||
private void sendCommonPayloadMessage(Account destinationAccount,
|
||||
@@ -891,28 +896,21 @@ public class MessageController {
|
||||
boolean online,
|
||||
boolean story,
|
||||
boolean urgent,
|
||||
byte[] payload) throws NoSuchUserException {
|
||||
try {
|
||||
Envelope.Builder messageBuilder = Envelope.newBuilder();
|
||||
long serverTimestamp = System.currentTimeMillis();
|
||||
byte[] payload) {
|
||||
|
||||
messageBuilder
|
||||
.setType(Type.UNIDENTIFIED_SENDER)
|
||||
.setTimestamp(timestamp == 0 ? serverTimestamp : timestamp)
|
||||
.setServerTimestamp(serverTimestamp)
|
||||
.setContent(ByteString.copyFrom(payload))
|
||||
.setStory(story)
|
||||
.setUrgent(urgent)
|
||||
.setDestinationUuid(serviceIdentifier.toServiceIdentifierString());
|
||||
final Envelope.Builder messageBuilder = Envelope.newBuilder();
|
||||
final long serverTimestamp = System.currentTimeMillis();
|
||||
|
||||
messageSender.sendMessage(destinationAccount, destinationDevice, messageBuilder.build(), online);
|
||||
} catch (NotPushRegisteredException e) {
|
||||
if (destinationDevice.isPrimary()) {
|
||||
throw new NoSuchUserException(e);
|
||||
} else {
|
||||
logger.debug("Not registered", e);
|
||||
}
|
||||
}
|
||||
messageBuilder
|
||||
.setType(Type.UNIDENTIFIED_SENDER)
|
||||
.setTimestamp(timestamp == 0 ? serverTimestamp : timestamp)
|
||||
.setServerTimestamp(serverTimestamp)
|
||||
.setContent(ByteString.copyFrom(payload))
|
||||
.setStory(story)
|
||||
.setUrgent(urgent)
|
||||
.setDestinationUuid(serviceIdentifier.toServiceIdentifierString());
|
||||
|
||||
messageSender.sendMessage(destinationAccount, destinationDevice, messageBuilder.build(), online);
|
||||
}
|
||||
|
||||
private void checkMessageRateLimit(AuthenticatedAccount source, Account destination, String userAgent)
|
||||
@@ -932,16 +930,22 @@ public class MessageController {
|
||||
}
|
||||
}
|
||||
|
||||
private void validateContentLength(final int contentLength, final String userAgent) {
|
||||
Metrics.summary(CONTENT_SIZE_DISTRIBUTION_NAME, Tags.of(UserAgentTagUtil.getPlatformTag(userAgent)))
|
||||
private void validateContentLength(final int contentLength, final boolean multiRecipientMessage, final String userAgent) {
|
||||
final boolean oversize = contentLength > MAX_MESSAGE_SIZE;
|
||||
|
||||
DistributionSummary.builder(CONTENT_SIZE_DISTRIBUTION_NAME)
|
||||
.tags(Tags.of(UserAgentTagUtil.getPlatformTag(userAgent),
|
||||
Tag.of("oversize", String.valueOf(oversize)),
|
||||
Tag.of("multiRecipientMessage", String.valueOf(multiRecipientMessage))))
|
||||
.publishPercentileHistogram(true)
|
||||
.register(Metrics.globalRegistry)
|
||||
.record(contentLength);
|
||||
|
||||
if (contentLength > MAX_MESSAGE_SIZE) {
|
||||
if (oversize) {
|
||||
Metrics.counter(REJECT_OVERSIZE_MESSAGE_COUNTER, Tags.of(UserAgentTagUtil.getPlatformTag(userAgent)))
|
||||
.increment();
|
||||
throw new WebApplicationException(Status.REQUEST_ENTITY_TOO_LARGE);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private void validateEnvelopeType(final int type, final String userAgent) {
|
||||
|
||||
-18
@@ -1,18 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2020 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public class NoSuchUserException extends Exception {
|
||||
|
||||
public NoSuchUserException(final UUID uuid) {
|
||||
super(uuid.toString());
|
||||
}
|
||||
|
||||
public NoSuchUserException(Exception e) {
|
||||
super(e);
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -447,7 +447,7 @@ public class ProfileController {
|
||||
return new BaseProfileResponse(account.getIdentityKey(IdentityType.ACI),
|
||||
account.getUnidentifiedAccessKey().map(UnidentifiedAccessChecksum::generateFor).orElse(null),
|
||||
account.isUnrestrictedUnidentifiedAccess(),
|
||||
new UserCapabilities(),
|
||||
UserCapabilities.createForAccount(account),
|
||||
profileBadgeConverter.convert(
|
||||
getAcceptableLanguagesForRequest(containerRequestContext),
|
||||
account.getBadges(),
|
||||
@@ -459,7 +459,7 @@ public class ProfileController {
|
||||
return new BaseProfileResponse(account.getIdentityKey(IdentityType.PNI),
|
||||
null,
|
||||
false,
|
||||
new UserCapabilities(),
|
||||
UserCapabilities.createForAccount(account),
|
||||
Collections.emptyList(),
|
||||
new PniServiceIdentifier(account.getPhoneNumberIdentifier()));
|
||||
}
|
||||
|
||||
+1
-2
@@ -11,8 +11,7 @@ import com.fasterxml.jackson.annotation.JsonTypeInfo;
|
||||
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type")
|
||||
@JsonSubTypes({
|
||||
@JsonSubTypes.Type(value = AnswerPushChallengeRequest.class, name = "rateLimitPushChallenge"),
|
||||
@JsonSubTypes.Type(value = AnswerCaptchaChallengeRequest.class, name = "captcha"),
|
||||
@JsonSubTypes.Type(value = AnswerCaptchaChallengeRequest.class, name = "recaptcha")
|
||||
@JsonSubTypes.Type(value = AnswerCaptchaChallengeRequest.class, name = "captcha")
|
||||
})
|
||||
public abstract class AnswerChallengeRequest {
|
||||
}
|
||||
+5
-7
@@ -5,16 +5,14 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
|
||||
public record UserCapabilities(
|
||||
// TODO: Remove the paymentActivation capability entirely sometime soon after 2024-06-30
|
||||
boolean paymentActivation,
|
||||
// TODO Remove the PNI and PNP capabilities entirely on or after 2024-05-18
|
||||
boolean pni,
|
||||
boolean pnp,
|
||||
// TODO Remove the giftBadges capability on or after 2024-05-26
|
||||
boolean giftBadges) {
|
||||
boolean deleteSync) {
|
||||
|
||||
public UserCapabilities() {
|
||||
this(true, true, true, true);
|
||||
public static UserCapabilities createForAccount(final Account account) {
|
||||
return new UserCapabilities(true, account.isDeleteSyncSupported());
|
||||
}
|
||||
}
|
||||
@@ -201,7 +201,8 @@ public class DevicesGrpcService extends ReactorDevicesGrpc.DevicesImplBase {
|
||||
d -> d.setCapabilities(new Device.DeviceCapabilities(
|
||||
request.getStorage(),
|
||||
request.getTransfer(),
|
||||
request.getPaymentActivation())))))
|
||||
request.getPaymentActivation(),
|
||||
request.getDeleteSync())))))
|
||||
.thenReturn(SetCapabilitiesResponse.newBuilder().build());
|
||||
}
|
||||
}
|
||||
@@ -39,7 +39,6 @@ class KeysGrpcHelper {
|
||||
: Flux.from(Mono.justOrEmpty(targetAccount.getDevice(targetDeviceId)));
|
||||
|
||||
return devices
|
||||
.filter(Device::isEnabled)
|
||||
.switchIfEmpty(Mono.error(Status.NOT_FOUND.asException()))
|
||||
.flatMap(device -> Flux.merge(
|
||||
Mono.fromFuture(() -> keysManager.takeEC(targetAccount.getIdentifier(identityType), device.getId())),
|
||||
|
||||
@@ -83,7 +83,7 @@ public class ProfileGrpcHelper {
|
||||
static UserCapabilities buildUserCapabilities(final org.whispersystems.textsecuregcm.entities.UserCapabilities capabilities) {
|
||||
return UserCapabilities.newBuilder()
|
||||
.setPaymentActivation(capabilities.paymentActivation())
|
||||
.setPni(capabilities.pni())
|
||||
.setDeleteSync(capabilities.deleteSync())
|
||||
.build();
|
||||
}
|
||||
|
||||
@@ -105,7 +105,7 @@ public class ProfileGrpcHelper {
|
||||
final ProfileBadgeConverter profileBadgeConverter) {
|
||||
final GetUnversionedProfileResponse.Builder responseBuilder = GetUnversionedProfileResponse.newBuilder()
|
||||
.setIdentityKey(ByteString.copyFrom(targetAccount.getIdentityKey(targetIdentifier.identityType()).serialize()))
|
||||
.setCapabilities(buildUserCapabilities(new org.whispersystems.textsecuregcm.entities.UserCapabilities()));
|
||||
.setCapabilities(buildUserCapabilities(org.whispersystems.textsecuregcm.entities.UserCapabilities.createForAccount(targetAccount)));
|
||||
|
||||
switch (targetIdentifier.identityType()) {
|
||||
case ACI -> {
|
||||
|
||||
@@ -21,6 +21,7 @@ import org.whispersystems.textsecuregcm.grpc.validators.EnumSpecifiedFieldValida
|
||||
import org.whispersystems.textsecuregcm.grpc.validators.ExactlySizeFieldValidator;
|
||||
import org.whispersystems.textsecuregcm.grpc.validators.FieldValidator;
|
||||
import org.whispersystems.textsecuregcm.grpc.validators.NonEmptyFieldValidator;
|
||||
import org.whispersystems.textsecuregcm.grpc.validators.PresentFieldValidator;
|
||||
import org.whispersystems.textsecuregcm.grpc.validators.RangeFieldValidator;
|
||||
import org.whispersystems.textsecuregcm.grpc.validators.SizeFieldValidator;
|
||||
|
||||
@@ -28,6 +29,7 @@ public class ValidatingInterceptor implements ServerInterceptor {
|
||||
|
||||
private final Map<String, FieldValidator> fieldValidators = Map.of(
|
||||
"org.signal.chat.require.nonEmpty", new NonEmptyFieldValidator(),
|
||||
"org.signal.chat.require.present", new PresentFieldValidator(),
|
||||
"org.signal.chat.require.specified", new EnumSpecifiedFieldValidator(),
|
||||
"org.signal.chat.require.e164", new E164FieldValidator(),
|
||||
"org.signal.chat.require.exactlySize", new ExactlySizeFieldValidator(),
|
||||
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package org.whispersystems.textsecuregcm.grpc.net;
|
||||
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import io.netty.channel.ChannelInboundHandlerAdapter;
|
||||
import io.netty.handler.codec.haproxy.HAProxyMessage;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* An HAProxy message handler handles decoded HAProxyMessage instances, removing itself from the pipeline once it has
|
||||
* either handled a proxy protocol message or determined that no such message is coming.
|
||||
*/
|
||||
public class HAProxyMessageHandler extends ChannelInboundHandlerAdapter {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(HAProxyMessageHandler.class);
|
||||
|
||||
@Override
|
||||
public void channelRead(final ChannelHandlerContext context, final Object message) throws Exception {
|
||||
if (message instanceof HAProxyMessage haProxyMessage) {
|
||||
// Some network/deployment configurations will send us a proxy protocol message, but we don't use it. We still
|
||||
// need to clear it from the pipeline to avoid confusing the TLS machinery, though.
|
||||
log.debug("Discarding HAProxy message: {}", haProxyMessage);
|
||||
haProxyMessage.release();
|
||||
} else {
|
||||
super.channelRead(context, message);
|
||||
}
|
||||
|
||||
// Regardless of the type of the first message, we'll only ever receive zero or one HAProxyMessages. After the first
|
||||
// message, all others will just be "normal" messages, and our work here is done.
|
||||
context.pipeline().remove(this);
|
||||
}
|
||||
}
|
||||
+8
-2
@@ -41,6 +41,7 @@ public class NoiseWebSocketTunnelServer implements Managed {
|
||||
|
||||
static final String AUTHENTICATED_SERVICE_PATH = "/authenticated";
|
||||
static final String ANONYMOUS_SERVICE_PATH = "/anonymous";
|
||||
static final String HEALTH_CHECK_PATH = "/health-check";
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(NoiseWebSocketTunnelServer.class);
|
||||
|
||||
@@ -72,7 +73,8 @@ public class NoiseWebSocketTunnelServer implements Managed {
|
||||
|
||||
sslContext = SslContextBuilder.forServer(tlsPrivateKey, tlsCertificateChain)
|
||||
.clientAuth(ClientAuth.NONE)
|
||||
.protocols(SslProtocols.TLS_v1_3)
|
||||
// Some load balancers require TLS 1.2 for health checks
|
||||
.protocols(SslProtocols.TLS_v1_3, SslProtocols.TLS_v1_2)
|
||||
.sslProvider(sslProvider)
|
||||
.build();
|
||||
} else {
|
||||
@@ -87,6 +89,10 @@ public class NoiseWebSocketTunnelServer implements Managed {
|
||||
.childHandler(new ChannelInitializer<SocketChannel>() {
|
||||
@Override
|
||||
protected void initChannel(SocketChannel socketChannel) {
|
||||
socketChannel.pipeline()
|
||||
.addLast(new ProxyProtocolDetectionHandler())
|
||||
.addLast(new HAProxyMessageHandler());
|
||||
|
||||
if (sslContext != null) {
|
||||
socketChannel.pipeline().addLast(sslContext.newHandler(socketChannel.alloc(), delegatedTaskExecutor));
|
||||
}
|
||||
@@ -96,7 +102,7 @@ public class NoiseWebSocketTunnelServer implements Managed {
|
||||
.addLast(new HttpObjectAggregator(Noise.MAX_PACKET_LEN))
|
||||
// The WebSocket opening handshake handler will remove itself from the pipeline once it has received a valid WebSocket upgrade
|
||||
// request and passed it down the pipeline
|
||||
.addLast(new WebSocketOpeningHandshakeHandler(AUTHENTICATED_SERVICE_PATH, ANONYMOUS_SERVICE_PATH))
|
||||
.addLast(new WebSocketOpeningHandshakeHandler(AUTHENTICATED_SERVICE_PATH, ANONYMOUS_SERVICE_PATH, HEALTH_CHECK_PATH))
|
||||
.addLast(new WebSocketServerProtocolHandler("/", true))
|
||||
.addLast(new RejectUnsupportedMessagesHandler())
|
||||
// The WebSocket handshake complete listener will replace itself with an appropriate Noise handshake handler once
|
||||
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
package org.whispersystems.textsecuregcm.grpc.net;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.netty.buffer.ByteBuf;
|
||||
import io.netty.buffer.CompositeByteBuf;
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import io.netty.channel.ChannelInboundHandlerAdapter;
|
||||
import io.netty.handler.codec.haproxy.HAProxyMessageDecoder;
|
||||
|
||||
/**
|
||||
* A proxy protocol detection handler watches for HAProxy PROXY protocol messages at the beginning of a TCP connection.
|
||||
* If a connection begins with a proxy message, this handler will add a {@link HAProxyMessageDecoder} to the pipeline.
|
||||
* In all cases, once this handler has determined that a connection does or does not begin with a proxy protocol
|
||||
* message, it will remove itself from the pipeline and pass any intercepted down the pipeline.
|
||||
*
|
||||
* @see <a href="https://www.haproxy.org/download/1.8/doc/proxy-protocol.txt">The PROXY protocol</a>
|
||||
*/
|
||||
public class ProxyProtocolDetectionHandler extends ChannelInboundHandlerAdapter {
|
||||
|
||||
private CompositeByteBuf accumulator;
|
||||
|
||||
@VisibleForTesting
|
||||
static final int PROXY_MESSAGE_DETECTION_BYTES = 12;
|
||||
|
||||
@Override
|
||||
public void handlerAdded(final ChannelHandlerContext context) {
|
||||
// We need at least 12 bytes to decide if a byte buffer contains a proxy protocol message. Assuming we only get
|
||||
// non-empty buffers, that means we'll need at most 12 sub-buffers to have a complete message. In virtually every
|
||||
// practical case, though, we'll be able to tell from the first packet.
|
||||
accumulator = new CompositeByteBuf(context.alloc(), false, PROXY_MESSAGE_DETECTION_BYTES);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void channelRead(final ChannelHandlerContext context, final Object message) throws Exception {
|
||||
if (message instanceof ByteBuf byteBuf) {
|
||||
accumulator.addComponent(true, byteBuf);
|
||||
|
||||
switch (HAProxyMessageDecoder.detectProtocol(accumulator).state()) {
|
||||
case NEEDS_MORE_DATA -> {
|
||||
}
|
||||
|
||||
case INVALID -> {
|
||||
// We have enough information to determine that this connection is NOT starting with a proxy protocol message,
|
||||
// and we can just pass the accumulated bytes through
|
||||
context.fireChannelRead(accumulator);
|
||||
|
||||
accumulator = null;
|
||||
context.pipeline().remove(this);
|
||||
}
|
||||
|
||||
case DETECTED -> {
|
||||
// We have enough information to know that we're dealing with a proxy protocol message; add appropriate
|
||||
// handlers and pass the accumulated bytes through
|
||||
context.pipeline().addAfter(context.name(), null, new HAProxyMessageDecoder());
|
||||
context.fireChannelRead(accumulator);
|
||||
|
||||
accumulator = null;
|
||||
context.pipeline().remove(this);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
super.channelRead(context, message);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handlerRemoved(final ChannelHandlerContext context) {
|
||||
if (accumulator != null) {
|
||||
accumulator.release();
|
||||
accumulator = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
+8
-1
@@ -19,10 +19,15 @@ class WebSocketOpeningHandshakeHandler extends ChannelInboundHandlerAdapter {
|
||||
|
||||
private final String authenticatedPath;
|
||||
private final String anonymousPath;
|
||||
private final String healthCheckPath;
|
||||
|
||||
WebSocketOpeningHandshakeHandler(final String authenticatedPath,
|
||||
final String anonymousPath,
|
||||
final String healthCheckPath) {
|
||||
|
||||
WebSocketOpeningHandshakeHandler(final String authenticatedPath, final String anonymousPath) {
|
||||
this.authenticatedPath = authenticatedPath;
|
||||
this.anonymousPath = anonymousPath;
|
||||
this.healthCheckPath = healthCheckPath;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -43,6 +48,8 @@ class WebSocketOpeningHandshakeHandler extends ChannelInboundHandlerAdapter {
|
||||
} else {
|
||||
closeConnectionWithStatus(context, request, HttpResponseStatus.UPGRADE_REQUIRED);
|
||||
}
|
||||
} else if (healthCheckPath.equals(request.uri())) {
|
||||
closeConnectionWithStatus(context, request, HttpResponseStatus.NO_CONTENT);
|
||||
} else {
|
||||
closeConnectionWithStatus(context, request, HttpResponseStatus.NOT_FOUND);
|
||||
}
|
||||
|
||||
+11
-1
@@ -12,6 +12,7 @@ import static org.whispersystems.textsecuregcm.grpc.validators.ValidatorUtils.in
|
||||
import com.google.protobuf.ByteString;
|
||||
import com.google.protobuf.Descriptors;
|
||||
import com.google.protobuf.GeneratedMessageV3;
|
||||
import com.google.protobuf.Message;
|
||||
import io.grpc.Status;
|
||||
import io.grpc.StatusException;
|
||||
import java.util.Set;
|
||||
@@ -91,7 +92,10 @@ public abstract class BaseFieldValidator<T> implements FieldValidator {
|
||||
validateBytesValue(extensionValueTyped, (ByteString) msg.getField(fd));
|
||||
case ENUM ->
|
||||
validateEnumValue(extensionValueTyped, (Descriptors.EnumValueDescriptor) msg.getField(fd));
|
||||
case FLOAT, DOUBLE, BOOL, MESSAGE, GROUP -> {
|
||||
case MESSAGE -> {
|
||||
validateMessageValue(extensionValueTyped, (Message) msg.getField(fd));
|
||||
}
|
||||
case FLOAT, DOUBLE, BOOL, GROUP -> {
|
||||
// at this moment, there are no validations specific to these types of fields
|
||||
}
|
||||
}
|
||||
@@ -140,6 +144,12 @@ public abstract class BaseFieldValidator<T> implements FieldValidator {
|
||||
throw internalError("`validateEnumValue` method needs to be implemented");
|
||||
}
|
||||
|
||||
protected void validateMessageValue(
|
||||
final T extensionValue,
|
||||
final Message message) throws StatusException {
|
||||
throw internalError("`validateMessageValue` method needs to be implemented");
|
||||
}
|
||||
|
||||
protected static boolean requireFlagExtension(final Object extensionValue) throws StatusException {
|
||||
if (extensionValue instanceof Boolean flagIsOn && flagIsOn) {
|
||||
return true;
|
||||
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.grpc.validators;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.grpc.validators.ValidatorUtils.invalidArgument;
|
||||
|
||||
import com.google.protobuf.Descriptors;
|
||||
import com.google.protobuf.Message;
|
||||
import io.grpc.StatusException;
|
||||
import java.util.Set;
|
||||
|
||||
public class PresentFieldValidator extends BaseFieldValidator<Boolean> {
|
||||
|
||||
public PresentFieldValidator() {
|
||||
super("present",
|
||||
Set.of(Descriptors.FieldDescriptor.Type.MESSAGE),
|
||||
MissingOptionalAction.FAIL,
|
||||
true);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Boolean resolveExtensionValue(final Object extensionValue) throws StatusException {
|
||||
return requireFlagExtension(extensionValue);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void validateMessageValue(final Boolean extensionValue, final Message msg) throws StatusException {
|
||||
if (msg == null) {
|
||||
throw invalidArgument("message expected to be present");
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -13,7 +13,7 @@ public class RateLimitChallengeOptionManager {
|
||||
|
||||
private final RateLimiters rateLimiters;
|
||||
|
||||
public static final String OPTION_CAPTCHA = "recaptcha";
|
||||
public static final String OPTION_CAPTCHA = "captcha";
|
||||
public static final String OPTION_PUSH_CHALLENGE = "pushChallenge";
|
||||
|
||||
public RateLimitChallengeOptionManager(final RateLimiters rateLimiters) {
|
||||
|
||||
@@ -8,6 +8,7 @@ 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,6 +79,16 @@ public interface RateLimiter {
|
||||
return clearAsync(accountUuid.toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* If the future throws a {@link RateLimitExceededException}, it will adapt it to ensure that
|
||||
* {@link RateLimitExceededException#isLegacy()} returns {@code false}
|
||||
*/
|
||||
static CompletionStage<Void> adaptLegacyException(final CompletionStage<Void> rateLimitFuture) {
|
||||
return rateLimitFuture.exceptionally(ExceptionUtils.exceptionallyHandler(RateLimitExceededException.class, e -> {
|
||||
throw ExceptionUtils.wrap(new RateLimitExceededException(e.getRetryDuration().orElse(null), false));
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* If the wrapped {@code validate()} call throws a {@link RateLimitExceededException}, it will adapt it to ensure that
|
||||
* {@link RateLimitExceededException#isLegacy()} returns {@code false}
|
||||
|
||||
@@ -18,8 +18,6 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
|
||||
|
||||
public enum For implements RateLimiterDescriptor {
|
||||
BACKUP_AUTH_CHECK("backupAuthCheck", false, new RateLimiterConfig(100, Duration.ofMinutes(15))),
|
||||
SMS_DESTINATION("smsDestination", false, new RateLimiterConfig(2, Duration.ofSeconds(30))),
|
||||
VERIFY("verify", false, new RateLimiterConfig(6, Duration.ofSeconds(30))),
|
||||
PIN("pin", false, new RateLimiterConfig(10, Duration.ofDays(1))),
|
||||
ATTACHMENT("attachmentCreate", false, new RateLimiterConfig(50, Duration.ofMillis(1200))),
|
||||
BACKUP_ATTACHMENT("backupAttachmentCreate", true, new RateLimiterConfig(10_000, Duration.ofSeconds(1))),
|
||||
@@ -118,14 +116,6 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
|
||||
return forDescriptor(For.ATTACHMENT);
|
||||
}
|
||||
|
||||
public RateLimiter getSmsDestinationLimiter() {
|
||||
return forDescriptor(For.SMS_DESTINATION);
|
||||
}
|
||||
|
||||
public RateLimiter getVerifyLimiter() {
|
||||
return forDescriptor(For.VERIFY);
|
||||
}
|
||||
|
||||
public RateLimiter getPinLimiter() {
|
||||
return forDescriptor(For.PIN);
|
||||
}
|
||||
|
||||
@@ -70,12 +70,14 @@ public final class MessageMetrics {
|
||||
|
||||
public void measureOutgoingMessageLatency(final long serverTimestamp,
|
||||
final String channel,
|
||||
final boolean isPrimaryDevice,
|
||||
final String userAgent,
|
||||
final ClientReleaseManager clientReleaseManager) {
|
||||
|
||||
final List<Tag> tags = new ArrayList<>(3);
|
||||
final List<Tag> tags = new ArrayList<>(4);
|
||||
tags.add(UserAgentTagUtil.getPlatformTag(userAgent));
|
||||
tags.add(Tag.of("channel", channel));
|
||||
tags.add(Tag.of("isPrimary", String.valueOf(isPrimaryDevice)));
|
||||
|
||||
UserAgentTagUtil.getClientVersionTag(userAgent, clientReleaseManager).ifPresent(tags::add);
|
||||
|
||||
|
||||
@@ -22,7 +22,6 @@ import io.micrometer.statsd.StatsdMeterRegistry;
|
||||
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.WhisperServerVersion;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.push.PushLatencyManager;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.util.Constants;
|
||||
|
||||
@@ -30,6 +29,8 @@ public class MetricsUtil {
|
||||
|
||||
public static final String PREFIX = "chat";
|
||||
|
||||
private static volatile boolean registeredMetrics = false;
|
||||
|
||||
/**
|
||||
* Returns a dot-separated ('.') name for the given class and name parts
|
||||
*/
|
||||
@@ -48,6 +49,13 @@ public class MetricsUtil {
|
||||
|
||||
public static void configureRegistries(final WhisperServerConfiguration config, final Environment environment,
|
||||
DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
|
||||
|
||||
if (registeredMetrics) {
|
||||
throw new IllegalStateException("Metric registries configured more than once");
|
||||
}
|
||||
|
||||
registeredMetrics = true;
|
||||
|
||||
SharedMetricRegistries.add(Constants.METRICS_NAME, environment.metrics());
|
||||
|
||||
{
|
||||
@@ -100,7 +108,6 @@ public class MetricsUtil {
|
||||
return MeterFilter.super.map(id);
|
||||
}
|
||||
})
|
||||
.meterFilter(MeterFilter.denyNameStartsWith(PushLatencyManager.TIMER_NAME + ".percentile"))
|
||||
.meterFilter(MeterFilter.denyNameStartsWith(MessageMetrics.DELIVERY_LATENCY_TIMER_NAME + ".percentile"));
|
||||
}
|
||||
|
||||
|
||||
+12
-1
@@ -5,7 +5,11 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.providers;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import io.dropwizard.util.DataSizeUnit;
|
||||
import io.micrometer.core.instrument.DistributionSummary;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.lang.annotation.Annotation;
|
||||
@@ -18,9 +22,9 @@ import javax.ws.rs.core.MultivaluedMap;
|
||||
import javax.ws.rs.core.NoContentException;
|
||||
import javax.ws.rs.ext.MessageBodyReader;
|
||||
import javax.ws.rs.ext.Provider;
|
||||
import org.signal.libsignal.protocol.SealedSenderMultiRecipientMessage;
|
||||
import org.signal.libsignal.protocol.InvalidMessageException;
|
||||
import org.signal.libsignal.protocol.InvalidVersionException;
|
||||
import org.signal.libsignal.protocol.SealedSenderMultiRecipientMessage;
|
||||
|
||||
@Provider
|
||||
@Consumes(MultiRecipientMessageProvider.MEDIA_TYPE)
|
||||
@@ -30,6 +34,11 @@ public class MultiRecipientMessageProvider implements MessageBodyReader<SealedSe
|
||||
public static final int MAX_RECIPIENT_COUNT = 5000;
|
||||
public static final int MAX_MESSAGE_SIZE = Math.toIntExact(32 + DataSizeUnit.KIBIBYTES.toBytes(256));
|
||||
|
||||
private static final DistributionSummary RECIPIENT_COUNT_DISTRIBUTION = DistributionSummary
|
||||
.builder(name(MultiRecipientMessageProvider.class, "recipients"))
|
||||
.publishPercentileHistogram(true)
|
||||
.register(Metrics.globalRegistry);
|
||||
|
||||
@Override
|
||||
public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
|
||||
return MEDIA_TYPE.equals(mediaType.toString()) && SealedSenderMultiRecipientMessage.class.isAssignableFrom(type);
|
||||
@@ -46,6 +55,8 @@ public class MultiRecipientMessageProvider implements MessageBodyReader<SealedSe
|
||||
|
||||
try {
|
||||
final SealedSenderMultiRecipientMessage message = SealedSenderMultiRecipientMessage.parse(fullMessage);
|
||||
RECIPIENT_COUNT_DISTRIBUTION.record(message.getRecipients().keySet().size());
|
||||
|
||||
if (message.getRecipients().values().stream().anyMatch(r -> message.messageSizeForRecipient(r) > MAX_MESSAGE_SIZE)) {
|
||||
throw new BadRequestException("message payload too large");
|
||||
}
|
||||
|
||||
@@ -23,6 +23,7 @@ import java.security.InvalidKeyException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import org.whispersystems.textsecuregcm.configuration.ApnConfiguration;
|
||||
@@ -156,20 +157,21 @@ public class APNSender implements Managed, PushNotificationSender {
|
||||
})
|
||||
.thenApplyAsync(response -> {
|
||||
final boolean accepted;
|
||||
final String rejectionReason;
|
||||
final Optional<String> rejectionReason;
|
||||
final boolean unregistered;
|
||||
|
||||
if (response.isAccepted()) {
|
||||
accepted = true;
|
||||
rejectionReason = null;
|
||||
rejectionReason = Optional.empty();
|
||||
unregistered = false;
|
||||
} else {
|
||||
accepted = false;
|
||||
rejectionReason = response.getRejectionReason().orElse("unknown");
|
||||
unregistered = ("Unregistered".equals(rejectionReason) || "BadDeviceToken".equals(rejectionReason));
|
||||
rejectionReason = response.getRejectionReason();
|
||||
unregistered = response.getRejectionReason().map(reason -> "Unregistered".equals(reason) || "BadDeviceToken".equals(reason) || "ExpiredToken".equals(reason))
|
||||
.orElse(false);
|
||||
}
|
||||
|
||||
return new SendPushNotificationResult(accepted, rejectionReason, unregistered);
|
||||
return new SendPushNotificationResult(accepted, rejectionReason, unregistered, response.getTokenInvalidationTimestamp());
|
||||
}, executor);
|
||||
}
|
||||
|
||||
|
||||
@@ -23,6 +23,7 @@ import io.micrometer.core.instrument.Timer;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.ThreadFactory;
|
||||
@@ -96,7 +97,7 @@ public class FcmSender implements PushNotificationSender {
|
||||
|
||||
return GoogleApiUtil.toCompletableFuture(firebaseMessagingClient.sendAsync(builder.build()), executor)
|
||||
.whenComplete((ignored, throwable) -> sample.stop(SEND_NOTIFICATION_TIMER))
|
||||
.thenApply(ignored -> new SendPushNotificationResult(true, null, false))
|
||||
.thenApply(ignored -> new SendPushNotificationResult(true, Optional.empty(), false, Optional.empty()))
|
||||
.exceptionally(throwable -> {
|
||||
if (ExceptionUtils.unwrap(throwable) instanceof final FirebaseMessagingException firebaseMessagingException) {
|
||||
final String errorCode;
|
||||
@@ -111,7 +112,7 @@ public class FcmSender implements PushNotificationSender {
|
||||
final boolean unregistered =
|
||||
firebaseMessagingException.getMessagingErrorCode() == MessagingErrorCode.UNREGISTERED;
|
||||
|
||||
return new SendPushNotificationResult(false, errorCode, unregistered);
|
||||
return new SendPushNotificationResult(false, Optional.of(errorCode), unregistered, Optional.empty());
|
||||
} else {
|
||||
throw ExceptionUtils.wrap(throwable);
|
||||
}
|
||||
|
||||
@@ -8,8 +8,6 @@ import static com.codahale.metrics.MetricRegistry.name;
|
||||
import static org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
|
||||
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisOperation;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesManager;
|
||||
@@ -32,7 +30,6 @@ public class MessageSender {
|
||||
private final ClientPresenceManager clientPresenceManager;
|
||||
private final MessagesManager messagesManager;
|
||||
private final PushNotificationManager pushNotificationManager;
|
||||
private final PushLatencyManager pushLatencyManager;
|
||||
|
||||
private static final String SEND_COUNTER_NAME = name(MessageSender.class, "sendMessage");
|
||||
private static final String CHANNEL_TAG_NAME = "channel";
|
||||
@@ -41,20 +38,17 @@ public class MessageSender {
|
||||
private static final String URGENT_TAG_NAME = "urgent";
|
||||
private static final String STORY_TAG_NAME = "story";
|
||||
private static final String SEALED_SENDER_TAG_NAME = "sealedSender";
|
||||
private static final String HAS_SPAM_REPORTING_TOKEN_TAG_NAME = "hasSpamReportingToken";
|
||||
|
||||
public MessageSender(ClientPresenceManager clientPresenceManager,
|
||||
MessagesManager messagesManager,
|
||||
PushNotificationManager pushNotificationManager,
|
||||
PushLatencyManager pushLatencyManager) {
|
||||
public MessageSender(final ClientPresenceManager clientPresenceManager,
|
||||
final MessagesManager messagesManager,
|
||||
final PushNotificationManager pushNotificationManager) {
|
||||
|
||||
this.clientPresenceManager = clientPresenceManager;
|
||||
this.messagesManager = messagesManager;
|
||||
this.pushNotificationManager = pushNotificationManager;
|
||||
this.pushLatencyManager = pushLatencyManager;
|
||||
}
|
||||
|
||||
public void sendMessage(final Account account, final Device device, final Envelope message, final boolean online)
|
||||
throws NotPushRegisteredException {
|
||||
public void sendMessage(final Account account, final Device device, final Envelope message, final boolean online) {
|
||||
|
||||
final String channel;
|
||||
|
||||
@@ -65,7 +59,7 @@ public class MessageSender {
|
||||
} else if (device.getFetchesMessages()) {
|
||||
channel = "websocket";
|
||||
} else {
|
||||
throw new AssertionError();
|
||||
channel = "none";
|
||||
}
|
||||
|
||||
final boolean clientPresent;
|
||||
@@ -87,13 +81,7 @@ public class MessageSender {
|
||||
if (!clientPresent) {
|
||||
try {
|
||||
pushNotificationManager.sendNewMessageNotification(account, device.getId(), message.getUrgent());
|
||||
|
||||
final boolean useVoip = StringUtils.isNotBlank(device.getVoipApnId());
|
||||
RedisOperation.unchecked(() -> pushLatencyManager.recordPushSent(account.getUuid(), device.getId(), useVoip, message.getUrgent()));
|
||||
} catch (final NotPushRegisteredException e) {
|
||||
if (!device.getFetchesMessages()) {
|
||||
throw e;
|
||||
}
|
||||
} catch (final NotPushRegisteredException ignored) {
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -104,8 +92,7 @@ public class MessageSender {
|
||||
CLIENT_ONLINE_TAG_NAME, String.valueOf(clientPresent),
|
||||
URGENT_TAG_NAME, String.valueOf(message.getUrgent()),
|
||||
STORY_TAG_NAME, String.valueOf(message.getStory()),
|
||||
SEALED_SENDER_TAG_NAME, String.valueOf(!message.hasSourceUuid()),
|
||||
HAS_SPAM_REPORTING_TOKEN_TAG_NAME, String.valueOf(message.getReportSpamToken() != null && !message.getReportSpamToken().isEmpty()))
|
||||
SEALED_SENDER_TAG_NAME, String.valueOf(!message.hasSourceUuid()))
|
||||
.increment();
|
||||
}
|
||||
}
|
||||
@@ -1,147 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.push;
|
||||
|
||||
import com.codahale.metrics.MetricRegistry;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.lettuce.core.SetArgs;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
|
||||
/**
|
||||
* Measures and records the latency between sending a push notification to a device and that device draining its queue
|
||||
* of messages.
|
||||
* <p/>
|
||||
* When the server sends a push notification to a device, the push latency manager creates a Redis key/value pair
|
||||
* mapping the current timestamp to the given device if such a mapping doesn't already exist. When a client connects and
|
||||
* clears its message queue, the push latency manager gets and clears the time of the initial push notification to that
|
||||
* device and records the time elapsed since the push notification timestamp as a latency observation.
|
||||
*/
|
||||
public class PushLatencyManager {
|
||||
|
||||
private final FaultTolerantRedisCluster redisCluster;
|
||||
private final ClientReleaseManager clientReleaseManager;
|
||||
|
||||
private final Clock clock;
|
||||
|
||||
public static final String TIMER_NAME = MetricRegistry.name(PushLatencyManager.class, "latency");
|
||||
private static final int TTL = (int) Duration.ofDays(1).toSeconds();
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(PushLatencyManager.class);
|
||||
|
||||
@VisibleForTesting
|
||||
enum PushType {
|
||||
STANDARD,
|
||||
VOIP
|
||||
}
|
||||
|
||||
record PushRecord(Instant timestamp, PushType pushType, Optional<Boolean> urgent) {
|
||||
}
|
||||
|
||||
public PushLatencyManager(final FaultTolerantRedisCluster redisCluster,
|
||||
final ClientReleaseManager clientReleaseManager) {
|
||||
|
||||
this(redisCluster, clientReleaseManager, Clock.systemUTC());
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
PushLatencyManager(final FaultTolerantRedisCluster redisCluster,
|
||||
final ClientReleaseManager clientReleaseManager,
|
||||
final Clock clock) {
|
||||
|
||||
this.redisCluster = redisCluster;
|
||||
this.clientReleaseManager = clientReleaseManager;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
void recordPushSent(final UUID accountUuid, final byte deviceId, final boolean isVoip, final boolean isUrgent) {
|
||||
try {
|
||||
final String recordJson = SystemMapper.jsonMapper().writeValueAsString(
|
||||
new PushRecord(Instant.now(clock), isVoip ? PushType.VOIP : PushType.STANDARD, Optional.of(isUrgent)));
|
||||
|
||||
redisCluster.useCluster(connection ->
|
||||
connection.async().set(getFirstUnacknowledgedPushKey(accountUuid, deviceId),
|
||||
recordJson,
|
||||
SetArgs.Builder.nx().ex(TTL)));
|
||||
} catch (final JsonProcessingException e) {
|
||||
// This should never happen
|
||||
log.error("Failed to write push latency record JSON", e);
|
||||
}
|
||||
}
|
||||
|
||||
void recordQueueRead(final UUID accountUuid, final byte deviceId, final String userAgentString) {
|
||||
takePushRecord(accountUuid, deviceId).thenAccept(pushRecord -> {
|
||||
if (pushRecord != null) {
|
||||
final Duration latency = Duration.between(pushRecord.timestamp(), Instant.now());
|
||||
|
||||
final List<Tag> tags = new ArrayList<>(3);
|
||||
|
||||
tags.add(UserAgentTagUtil.getPlatformTag(userAgentString));
|
||||
tags.add(Tag.of("pushType", pushRecord.pushType().name().toLowerCase()));
|
||||
|
||||
UserAgentTagUtil.getClientVersionTag(userAgentString, clientReleaseManager)
|
||||
.ifPresent(tags::add);
|
||||
|
||||
pushRecord.urgent().ifPresent(urgent -> tags.add(Tag.of("urgent", String.valueOf(urgent))));
|
||||
|
||||
Timer.builder(TIMER_NAME)
|
||||
.publishPercentileHistogram(true)
|
||||
.tags(tags)
|
||||
.register(Metrics.globalRegistry)
|
||||
.record(latency);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
CompletableFuture<PushRecord> takePushRecord(final UUID accountUuid, final byte deviceId) {
|
||||
final String key = getFirstUnacknowledgedPushKey(accountUuid, deviceId);
|
||||
|
||||
return redisCluster.withCluster(connection -> {
|
||||
final CompletableFuture<PushRecord> getFuture = connection.async().get(key).toCompletableFuture()
|
||||
.thenApply(recordJson -> {
|
||||
if (StringUtils.isNotEmpty(recordJson)) {
|
||||
try {
|
||||
return SystemMapper.jsonMapper().readValue(recordJson, PushRecord.class);
|
||||
} catch (JsonProcessingException e) {
|
||||
return null;
|
||||
}
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
});
|
||||
|
||||
getFuture.whenComplete((record, cause) -> {
|
||||
if (cause == null) {
|
||||
connection.async().del(key);
|
||||
}
|
||||
});
|
||||
|
||||
return getFuture;
|
||||
});
|
||||
}
|
||||
|
||||
private static String getFirstUnacknowledgedPushKey(final UUID accountUuid, final byte deviceId) {
|
||||
return "push_latency::v2::" + accountUuid.toString() + "::" + deviceId;
|
||||
}
|
||||
}
|
||||
+125
-84
@@ -10,7 +10,9 @@ import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import java.time.Instant;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.function.BiConsumer;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
@@ -20,7 +22,6 @@ import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
public class PushNotificationManager {
|
||||
|
||||
@@ -28,59 +29,59 @@ public class PushNotificationManager {
|
||||
private final APNSender apnSender;
|
||||
private final FcmSender fcmSender;
|
||||
private final ApnPushNotificationScheduler apnPushNotificationScheduler;
|
||||
private final PushLatencyManager pushLatencyManager;
|
||||
|
||||
private static final String SENT_NOTIFICATION_COUNTER_NAME = name(PushNotificationManager.class, "sentPushNotification");
|
||||
private static final String FAILED_NOTIFICATION_COUNTER_NAME = name(PushNotificationManager.class, "failedPushNotification");
|
||||
private static final String DEVICE_TOKEN_UNREGISTERED_COUNTER_NAME = name(PushNotificationManager.class, "deviceTokenUnregistered");
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(PushNotificationManager.class);
|
||||
|
||||
public PushNotificationManager(final AccountsManager accountsManager,
|
||||
final APNSender apnSender,
|
||||
final FcmSender fcmSender,
|
||||
final ApnPushNotificationScheduler apnPushNotificationScheduler,
|
||||
final PushLatencyManager pushLatencyManager) {
|
||||
final ApnPushNotificationScheduler apnPushNotificationScheduler) {
|
||||
|
||||
this.accountsManager = accountsManager;
|
||||
this.apnSender = apnSender;
|
||||
this.fcmSender = fcmSender;
|
||||
this.apnPushNotificationScheduler = apnPushNotificationScheduler;
|
||||
this.pushLatencyManager = pushLatencyManager;
|
||||
}
|
||||
|
||||
public void sendNewMessageNotification(final Account destination, final byte destinationDeviceId, final boolean urgent) throws NotPushRegisteredException {
|
||||
public CompletableFuture<Optional<SendPushNotificationResult>> sendNewMessageNotification(final Account destination, final byte destinationDeviceId, final boolean urgent) throws NotPushRegisteredException {
|
||||
final Device device = destination.getDevice(destinationDeviceId).orElseThrow(NotPushRegisteredException::new);
|
||||
final Pair<String, PushNotification.TokenType> tokenAndType = getToken(device);
|
||||
|
||||
sendNotification(new PushNotification(tokenAndType.first(), tokenAndType.second(),
|
||||
return sendNotification(new PushNotification(tokenAndType.first(), tokenAndType.second(),
|
||||
PushNotification.NotificationType.NOTIFICATION, null, destination, device, urgent));
|
||||
}
|
||||
|
||||
public void sendRegistrationChallengeNotification(final String deviceToken, final PushNotification.TokenType tokenType, final String challengeToken) {
|
||||
sendNotification(new PushNotification(deviceToken, tokenType, PushNotification.NotificationType.CHALLENGE, challengeToken, null, null, true));
|
||||
public CompletableFuture<SendPushNotificationResult> sendRegistrationChallengeNotification(final String deviceToken, final PushNotification.TokenType tokenType, final String challengeToken) {
|
||||
return sendNotification(new PushNotification(deviceToken, tokenType, PushNotification.NotificationType.CHALLENGE, challengeToken, null, null, true))
|
||||
.thenApply(maybeResponse -> maybeResponse.orElseThrow(() -> new AssertionError("Responses must be present for urgent notifications")));
|
||||
}
|
||||
|
||||
public void sendRateLimitChallengeNotification(final Account destination, final String challengeToken)
|
||||
public CompletableFuture<SendPushNotificationResult> sendRateLimitChallengeNotification(final Account destination, final String challengeToken)
|
||||
throws NotPushRegisteredException {
|
||||
|
||||
final Device device = destination.getPrimaryDevice();
|
||||
final Pair<String, PushNotification.TokenType> tokenAndType = getToken(device);
|
||||
|
||||
sendNotification(new PushNotification(tokenAndType.first(), tokenAndType.second(),
|
||||
PushNotification.NotificationType.RATE_LIMIT_CHALLENGE, challengeToken, destination, device, true));
|
||||
return sendNotification(new PushNotification(tokenAndType.first(), tokenAndType.second(),
|
||||
PushNotification.NotificationType.RATE_LIMIT_CHALLENGE, challengeToken, destination, device, true))
|
||||
.thenApply(maybeResponse -> maybeResponse.orElseThrow(() -> new AssertionError("Responses must be present for urgent notifications")));
|
||||
}
|
||||
|
||||
public void sendAttemptLoginNotification(final Account destination, final String context) throws NotPushRegisteredException {
|
||||
public CompletableFuture<SendPushNotificationResult> sendAttemptLoginNotification(final Account destination, final String context) throws NotPushRegisteredException {
|
||||
final Device device = destination.getDevice(Device.PRIMARY_ID).orElseThrow(NotPushRegisteredException::new);
|
||||
final Pair<String, PushNotification.TokenType> tokenAndType = getToken(device);
|
||||
|
||||
sendNotification(new PushNotification(tokenAndType.first(), tokenAndType.second(),
|
||||
return sendNotification(new PushNotification(tokenAndType.first(), tokenAndType.second(),
|
||||
PushNotification.NotificationType.ATTEMPT_LOGIN_NOTIFICATION_HIGH_PRIORITY,
|
||||
context, destination, device, true));
|
||||
context, destination, device, true))
|
||||
.thenApply(maybeResponse -> maybeResponse.orElseThrow(() -> new AssertionError("Responses must be present for urgent notifications")));
|
||||
}
|
||||
|
||||
public void handleMessagesRetrieved(final Account account, final Device device, final String userAgent) {
|
||||
RedisOperation.unchecked(() -> pushLatencyManager.recordQueueRead(account.getUuid(), device.getId(), userAgent));
|
||||
apnPushNotificationScheduler.cancelScheduledNotifications(account, device).whenComplete(logErrors());
|
||||
}
|
||||
|
||||
@@ -102,59 +103,66 @@ public class PushNotificationManager {
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
void sendNotification(final PushNotification pushNotification) {
|
||||
CompletableFuture<Optional<SendPushNotificationResult>> sendNotification(final PushNotification pushNotification) {
|
||||
if (pushNotification.tokenType() == PushNotification.TokenType.APN && !pushNotification.urgent()) {
|
||||
// APNs imposes a per-device limit on background push notifications; schedule a notification for some time in the
|
||||
// future (possibly even now!) rather than sending a notification directly
|
||||
apnPushNotificationScheduler
|
||||
return apnPushNotificationScheduler
|
||||
.scheduleBackgroundNotification(pushNotification.destination(), pushNotification.destinationDevice())
|
||||
.whenComplete(logErrors());
|
||||
|
||||
} else {
|
||||
final PushNotificationSender sender = switch (pushNotification.tokenType()) {
|
||||
case FCM -> fcmSender;
|
||||
case APN, APN_VOIP -> apnSender;
|
||||
};
|
||||
|
||||
sender.sendNotification(pushNotification).whenComplete((result, throwable) -> {
|
||||
if (throwable == null) {
|
||||
Tags tags = Tags.of("tokenType", pushNotification.tokenType().name(),
|
||||
"notificationType", pushNotification.notificationType().name(),
|
||||
"urgent", String.valueOf(pushNotification.urgent()),
|
||||
"accepted", String.valueOf(result.accepted()),
|
||||
"unregistered", String.valueOf(result.unregistered()));
|
||||
|
||||
if (StringUtils.isNotBlank(result.errorCode())) {
|
||||
tags = tags.and("errorCode", result.errorCode());
|
||||
}
|
||||
|
||||
Metrics.counter(SENT_NOTIFICATION_COUNTER_NAME, tags).increment();
|
||||
|
||||
if (result.unregistered() && pushNotification.destination() != null
|
||||
&& pushNotification.destinationDevice() != null) {
|
||||
handleDeviceUnregistered(pushNotification.destination(), pushNotification.destinationDevice());
|
||||
}
|
||||
|
||||
if (result.accepted() &&
|
||||
pushNotification.tokenType() == PushNotification.TokenType.APN_VOIP &&
|
||||
pushNotification.notificationType() == PushNotification.NotificationType.NOTIFICATION &&
|
||||
pushNotification.destination() != null &&
|
||||
pushNotification.destinationDevice() != null) {
|
||||
|
||||
apnPushNotificationScheduler.scheduleRecurringVoipNotification(
|
||||
pushNotification.destination(),
|
||||
pushNotification.destinationDevice())
|
||||
.whenComplete(logErrors());
|
||||
}
|
||||
} else {
|
||||
logger.debug("Failed to deliver {} push notification to {} ({})",
|
||||
pushNotification.notificationType(), pushNotification.deviceToken(), pushNotification.tokenType(),
|
||||
throwable);
|
||||
|
||||
Metrics.counter(FAILED_NOTIFICATION_COUNTER_NAME, "cause", throwable.getClass().getSimpleName()).increment();
|
||||
}
|
||||
});
|
||||
.whenComplete(logErrors())
|
||||
.thenApply(ignored -> Optional.<SendPushNotificationResult>empty())
|
||||
.toCompletableFuture();
|
||||
}
|
||||
|
||||
final PushNotificationSender sender = switch (pushNotification.tokenType()) {
|
||||
case FCM -> fcmSender;
|
||||
case APN, APN_VOIP -> apnSender;
|
||||
};
|
||||
|
||||
return sender.sendNotification(pushNotification).whenComplete((result, throwable) -> {
|
||||
if (throwable == null) {
|
||||
Tags tags = Tags.of("tokenType", pushNotification.tokenType().name(),
|
||||
"notificationType", pushNotification.notificationType().name(),
|
||||
"urgent", String.valueOf(pushNotification.urgent()),
|
||||
"accepted", String.valueOf(result.accepted()),
|
||||
"unregistered", String.valueOf(result.unregistered()));
|
||||
|
||||
if (result.errorCode().isPresent()) {
|
||||
tags = tags.and("errorCode", result.errorCode().get());
|
||||
}
|
||||
|
||||
Metrics.counter(SENT_NOTIFICATION_COUNTER_NAME, tags).increment();
|
||||
|
||||
if (result.unregistered() && pushNotification.destination() != null
|
||||
&& pushNotification.destinationDevice() != null) {
|
||||
|
||||
handleDeviceUnregistered(pushNotification.destination(),
|
||||
pushNotification.destinationDevice(),
|
||||
pushNotification.tokenType(),
|
||||
result.errorCode(),
|
||||
result.unregisteredTimestamp());
|
||||
}
|
||||
|
||||
if (result.accepted() &&
|
||||
pushNotification.tokenType() == PushNotification.TokenType.APN_VOIP &&
|
||||
pushNotification.notificationType() == PushNotification.NotificationType.NOTIFICATION &&
|
||||
pushNotification.destination() != null &&
|
||||
pushNotification.destinationDevice() != null) {
|
||||
|
||||
apnPushNotificationScheduler.scheduleRecurringVoipNotification(
|
||||
pushNotification.destination(),
|
||||
pushNotification.destinationDevice())
|
||||
.whenComplete(logErrors());
|
||||
}
|
||||
} else {
|
||||
logger.debug("Failed to deliver {} push notification to {} ({})",
|
||||
pushNotification.notificationType(), pushNotification.deviceToken(), pushNotification.tokenType(),
|
||||
throwable);
|
||||
|
||||
Metrics.counter(FAILED_NOTIFICATION_COUNTER_NAME, "cause", throwable.getClass().getSimpleName()).increment();
|
||||
}
|
||||
})
|
||||
.thenApply(Optional::of);
|
||||
}
|
||||
|
||||
private static <T> BiConsumer<T, Throwable> logErrors() {
|
||||
@@ -165,27 +173,60 @@ public class PushNotificationManager {
|
||||
};
|
||||
}
|
||||
|
||||
private void handleDeviceUnregistered(final Account account, final Device device) {
|
||||
if (StringUtils.isNotBlank(device.getGcmId())) {
|
||||
if (device.getUninstalledFeedbackTimestamp() == 0) {
|
||||
// Reread the account to avoid marking the caller's account as stale. The consumers of this class tend to
|
||||
// promise not to modify accounts. There's no need to force the caller to be considered mutable just for
|
||||
// updating an uninstalled feedback timestamp though.
|
||||
final Optional<Account> rereadAccount = accountsManager.getByAccountIdentifier(account.getUuid());
|
||||
if (rereadAccount.isEmpty()) {
|
||||
// don't bother adding the uninstalled timestamp, the account is gone
|
||||
return;
|
||||
}
|
||||
final Optional<Device> rereadDevice = rereadAccount.get().getDevice(device.getId());
|
||||
if (rereadDevice.map(Device::getUninstalledFeedbackTimestamp).orElse(-1L) != 0) {
|
||||
// don't bother adding the uninstalled timestamp, the device is gone or already updated
|
||||
return;
|
||||
}
|
||||
accountsManager.updateDevice(rereadAccount.get(), device.getId(), d ->
|
||||
d.setUninstalledFeedbackTimestamp(Util.todayInMillis()));
|
||||
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
|
||||
private void handleDeviceUnregistered(final Account account,
|
||||
final Device device,
|
||||
final PushNotification.TokenType tokenType,
|
||||
final Optional<String> maybeErrorCode,
|
||||
final Optional<Instant> maybeTokenInvalidationTimestamp) {
|
||||
|
||||
final boolean tokenExpired = maybeTokenInvalidationTimestamp.map(tokenInvalidationTimestamp ->
|
||||
tokenInvalidationTimestamp.isAfter(Instant.ofEpochMilli(device.getPushTimestamp()))).orElse(true);
|
||||
|
||||
if (tokenExpired) {
|
||||
if (tokenType == PushNotification.TokenType.APN || tokenType == PushNotification.TokenType.APN_VOIP) {
|
||||
apnPushNotificationScheduler.cancelScheduledNotifications(account, device).whenComplete(logErrors());
|
||||
}
|
||||
} else {
|
||||
apnPushNotificationScheduler.cancelScheduledNotifications(account, device).whenComplete(logErrors());
|
||||
|
||||
clearPushToken(account, device, tokenType);
|
||||
}
|
||||
Metrics.counter(DEVICE_TOKEN_UNREGISTERED_COUNTER_NAME,
|
||||
"errorCode", maybeErrorCode.orElse("unknown"),
|
||||
"isPrimary", String.valueOf(device.isPrimary()),
|
||||
"hasUnregisteredTimestamp", String.valueOf(maybeTokenInvalidationTimestamp.isPresent()),
|
||||
"tokenType", tokenType.name(),
|
||||
"tokenExpired", String.valueOf(tokenExpired)).increment();
|
||||
}
|
||||
|
||||
private void clearPushToken(final Account account, final Device device, final PushNotification.TokenType tokenType) {
|
||||
final String originalToken = getPushToken(device, tokenType);
|
||||
|
||||
if (originalToken == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Reread the account to avoid marking the caller's account as stale. The consumers of this class tend to
|
||||
// promise not to modify accounts. There's no need to force the caller to be considered mutable just for
|
||||
// updating an uninstalled feedback timestamp though.
|
||||
accountsManager.getByAccountIdentifier(account.getUuid()).ifPresent(rereadAccount ->
|
||||
rereadAccount.getDevice(device.getId()).ifPresent(rereadDevice ->
|
||||
accountsManager.updateDevice(rereadAccount, device.getId(), d -> {
|
||||
// Don't clear the token if it's already changed
|
||||
if (originalToken.equals(getPushToken(d, tokenType))) {
|
||||
switch (tokenType) {
|
||||
case FCM -> d.setGcmId(null);
|
||||
case APN -> d.setApnId(null);
|
||||
case APN_VOIP -> d.setVoipApnId(null);
|
||||
}
|
||||
}
|
||||
})));
|
||||
}
|
||||
|
||||
private static String getPushToken(final Device device, final PushNotification.TokenType tokenType) {
|
||||
return switch (tokenType) {
|
||||
case FCM -> device.getGcmId();
|
||||
case APN -> device.getApnId();
|
||||
case APN_VOIP -> device.getVoipApnId();
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -55,8 +55,6 @@ public class ReceiptSender {
|
||||
for (final Device destinationDevice : destinationAccount.getDevices()) {
|
||||
try {
|
||||
messageSender.sendMessage(destinationAccount, destinationDevice, message.build(), false);
|
||||
} catch (final NotPushRegisteredException e) {
|
||||
logger.debug("User no longer push registered for delivery receipt: {}", e.getMessage());
|
||||
} catch (final Exception e) {
|
||||
logger.warn("Could not send delivery receipt", e);
|
||||
}
|
||||
|
||||
+6
-2
@@ -5,7 +5,11 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.push;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
import java.time.Instant;
|
||||
import java.util.Optional;
|
||||
|
||||
public record SendPushNotificationResult(boolean accepted, @Nullable String errorCode, boolean unregistered) {
|
||||
public record SendPushNotificationResult(boolean accepted,
|
||||
Optional<String> errorCode,
|
||||
boolean unregistered,
|
||||
Optional<Instant> unregisteredTimestamp) {
|
||||
}
|
||||
+10
-2
@@ -18,6 +18,7 @@ import io.lettuce.core.cluster.ClusterClientOptions;
|
||||
import io.lettuce.core.cluster.ClusterTopologyRefreshOptions;
|
||||
import io.lettuce.core.cluster.RedisClusterClient;
|
||||
import io.lettuce.core.cluster.api.StatefulRedisClusterConnection;
|
||||
import io.lettuce.core.cluster.event.ClusterTopologyChangedEvent;
|
||||
import io.lettuce.core.cluster.pubsub.StatefulRedisClusterPubSubConnection;
|
||||
import io.lettuce.core.codec.ByteArrayCodec;
|
||||
import io.lettuce.core.resource.ClientResources;
|
||||
@@ -73,9 +74,10 @@ public class FaultTolerantRedisCluster {
|
||||
|
||||
this.name = name;
|
||||
|
||||
final LettuceShardCircuitBreaker lettuceShardCircuitBreaker = new LettuceShardCircuitBreaker(name,
|
||||
circuitBreakerConfig.toCircuitBreakerConfig(), Schedulers.newSingle("topology-changed-" + name, true));
|
||||
this.clusterClient = RedisClusterClient.create(
|
||||
clientResourcesBuilder.nettyCustomizer(
|
||||
new LettuceShardCircuitBreaker(name, circuitBreakerConfig.toCircuitBreakerConfig())).
|
||||
clientResourcesBuilder.nettyCustomizer(lettuceShardCircuitBreaker).
|
||||
build(),
|
||||
redisUris);
|
||||
this.clusterClient.setOptions(ClusterClientOptions.builder()
|
||||
@@ -91,9 +93,15 @@ public class FaultTolerantRedisCluster {
|
||||
.publishOnScheduler(true)
|
||||
.build());
|
||||
|
||||
lettuceShardCircuitBreaker.setEventBus(clusterClient.getResources().eventBus());
|
||||
|
||||
this.stringConnection = clusterClient.connect();
|
||||
this.binaryConnection = clusterClient.connect(ByteArrayCodec.INSTANCE);
|
||||
|
||||
// create a synthetic topology changed event to notify shard circuit breakers of initial upstreams
|
||||
clusterClient.getResources().eventBus().publish(
|
||||
new ClusterTopologyChangedEvent(Collections.emptyList(), clusterClient.getPartitions().getPartitions()));
|
||||
|
||||
this.retry = Retry.of(name + "-retry", retryConfiguration.toRetryConfigBuilder()
|
||||
.retryOnException(exception -> exception instanceof RedisCommandTimeoutException).build());
|
||||
final RetryConfig topologyChangedEventRetryConfig = RetryConfig.custom()
|
||||
|
||||
+110
-5
@@ -10,6 +10,9 @@ import io.github.resilience4j.circuitbreaker.CallNotPermittedException;
|
||||
import io.github.resilience4j.circuitbreaker.CircuitBreaker;
|
||||
import io.github.resilience4j.circuitbreaker.CircuitBreakerConfig;
|
||||
import io.lettuce.core.RedisNoScriptException;
|
||||
import io.lettuce.core.cluster.event.ClusterTopologyChangedEvent;
|
||||
import io.lettuce.core.cluster.models.partitions.RedisClusterNode;
|
||||
import io.lettuce.core.event.EventBus;
|
||||
import io.lettuce.core.protocol.CommandHandler;
|
||||
import io.lettuce.core.protocol.CompleteableCommand;
|
||||
import io.lettuce.core.protocol.RedisCommand;
|
||||
@@ -21,28 +24,92 @@ import io.netty.channel.ChannelHandlerContext;
|
||||
import io.netty.channel.ChannelPromise;
|
||||
import java.net.SocketAddress;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.StreamSupport;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.util.CircuitBreakerUtil;
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
|
||||
/**
|
||||
* Adds a circuit breaker to every Netty {@link Channel} that gets created, so that a single unhealthy shard does not
|
||||
* impact all cluster operations.
|
||||
* <p>
|
||||
* For metrics to be registered, users <em>must</em> create a synthetic {@link ClusterTopologyChangedEvent} after the
|
||||
* initial connection. For example:
|
||||
* <pre>
|
||||
* clusterClient.connect();
|
||||
* clusterClient.getResources().eventBus().publish(
|
||||
* new ClusterTopologyChangedEvent(Collections.emptyList(), clusterClient.getPartitions().getPartitions()));
|
||||
* </pre>
|
||||
*/
|
||||
public class LettuceShardCircuitBreaker implements NettyCustomizer {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(LettuceShardCircuitBreaker.class);
|
||||
|
||||
private final String clusterName;
|
||||
private final CircuitBreakerConfig circuitBreakerConfig;
|
||||
private final Scheduler scheduler;
|
||||
// this set will be shared with all child channel breakers
|
||||
private final Set<String> upstreamAddresses = ConcurrentHashMap.newKeySet();
|
||||
// The EventBus is not available at construction time, because it is one of the client
|
||||
// resources, which cannot be built without this NettyCustomizer
|
||||
private EventBus eventBus;
|
||||
|
||||
public LettuceShardCircuitBreaker(final String clusterName, final CircuitBreakerConfig circuitBreakerConfig) {
|
||||
public LettuceShardCircuitBreaker(final String clusterName, final CircuitBreakerConfig circuitBreakerConfig,
|
||||
final Scheduler scheduler) {
|
||||
this.clusterName = clusterName;
|
||||
this.circuitBreakerConfig = circuitBreakerConfig;
|
||||
this.scheduler = scheduler;
|
||||
}
|
||||
|
||||
private static String toShardAddress(final RedisClusterNode redisClusterNode) {
|
||||
return "%s:%s".formatted(redisClusterNode.getUri().getHost(), redisClusterNode.getUri().getPort());
|
||||
}
|
||||
|
||||
void setEventBus(final EventBus eventBus) {
|
||||
this.eventBus = eventBus;
|
||||
|
||||
eventBus.get()
|
||||
.filter(e -> e instanceof ClusterTopologyChangedEvent)
|
||||
.map(e -> (ClusterTopologyChangedEvent) e)
|
||||
.subscribeOn(scheduler)
|
||||
.subscribe(event -> {
|
||||
|
||||
final Set<String> currentUpstreams = event.after().stream()
|
||||
.filter(node -> node.getRole().isUpstream())
|
||||
.map(LettuceShardCircuitBreaker::toShardAddress)
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
final Set<String> previousUpstreams = event.before().stream()
|
||||
.filter(node -> node.getRole().isUpstream())
|
||||
.map(LettuceShardCircuitBreaker::toShardAddress)
|
||||
.collect(Collectors.toSet());
|
||||
if (previousUpstreams.removeAll(currentUpstreams)) {
|
||||
logger.info("No longer upstream in cluster {}: {}", clusterName, StringUtils.join(previousUpstreams, ", "));
|
||||
}
|
||||
|
||||
// Channels may be created at any time, not just immediately after the cluster client connect()s or when topology
|
||||
// changes, so we maintain a set that can be queried by channel handlers during their connect() method.
|
||||
upstreamAddresses.addAll(currentUpstreams);
|
||||
upstreamAddresses.removeAll(previousUpstreams);
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterChannelInitialized(final Channel channel) {
|
||||
|
||||
if (eventBus == null) {
|
||||
throw new IllegalStateException("Event bus must be set before channel customization can occur");
|
||||
}
|
||||
|
||||
final ChannelCircuitBreakerHandler channelCircuitBreakerHandler = new ChannelCircuitBreakerHandler(clusterName,
|
||||
circuitBreakerConfig);
|
||||
circuitBreakerConfig, upstreamAddresses, eventBus, scheduler);
|
||||
|
||||
final String commandHandlerName = StreamSupport.stream(channel.pipeline().spliterator(), false)
|
||||
.filter(entry -> entry.getValue() instanceof CommandHandler)
|
||||
@@ -60,13 +127,48 @@ public class LettuceShardCircuitBreaker implements NettyCustomizer {
|
||||
|
||||
private final String clusterName;
|
||||
private final CircuitBreakerConfig circuitBreakerConfig;
|
||||
private final AtomicBoolean registeredMetrics = new AtomicBoolean(false);
|
||||
private final Set<String> upstreamAddresses;
|
||||
|
||||
private String shardAddress;
|
||||
|
||||
@VisibleForTesting
|
||||
CircuitBreaker breaker;
|
||||
|
||||
public ChannelCircuitBreakerHandler(final String name, CircuitBreakerConfig circuitBreakerConfig) {
|
||||
public ChannelCircuitBreakerHandler(final String name, final CircuitBreakerConfig circuitBreakerConfig,
|
||||
final Set<String> upstreamAddresses,
|
||||
final EventBus eventBus, final Scheduler scheduler) {
|
||||
this.clusterName = name;
|
||||
this.circuitBreakerConfig = circuitBreakerConfig;
|
||||
this.upstreamAddresses = upstreamAddresses;
|
||||
|
||||
eventBus.get()
|
||||
.filter(e -> e instanceof ClusterTopologyChangedEvent)
|
||||
.map(e -> (ClusterTopologyChangedEvent) e)
|
||||
.subscribeOn(scheduler)
|
||||
.subscribe(event -> {
|
||||
if (shardAddress == null) {
|
||||
logger.warn("Received a topology changed event without a shard address");
|
||||
return;
|
||||
}
|
||||
|
||||
final Set<String> newUpstreams = event.after().stream().filter(node -> node.getRole().isUpstream())
|
||||
.map(LettuceShardCircuitBreaker::toShardAddress)
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
if (newUpstreams.contains(shardAddress)) {
|
||||
registerMetrics();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void registerMetrics() {
|
||||
// Registering metrics is not idempotent--some counters are added as event listeners,
|
||||
// and there would be duplicated calls to increment()
|
||||
if (registeredMetrics.compareAndSet(false, true)) {
|
||||
logger.info("Registered metrics for: {}/{}", clusterName, shardAddress);
|
||||
CircuitBreakerUtil.registerMetrics(breaker, getClass(), Tags.of(CLUSTER_TAG_NAME, clusterName));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -79,9 +181,12 @@ public class LettuceShardCircuitBreaker implements NettyCustomizer {
|
||||
// match remote address, as it is inherited from the Bootstrap attributes and not updated for the Channel connection
|
||||
|
||||
// In some cases, like the default connection, the remote address includes the DNS hostname, which we want to exclude.
|
||||
final String shardAddress = StringUtils.substringAfter(remoteAddress.toString(), "/");
|
||||
shardAddress = StringUtils.substringAfter(remoteAddress.toString(), "/");
|
||||
breaker = CircuitBreaker.of("%s/%s-breaker".formatted(clusterName, shardAddress), circuitBreakerConfig);
|
||||
CircuitBreakerUtil.registerMetrics(breaker, getClass(), Tags.of(CLUSTER_TAG_NAME, clusterName));
|
||||
|
||||
if (upstreamAddresses.contains(shardAddress)) {
|
||||
registerMetrics();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -0,0 +1,222 @@
|
||||
package org.whispersystems.textsecuregcm.scheduler;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.util.retry.Retry;
|
||||
import software.amazon.awssdk.core.SdkBytes;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
|
||||
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
|
||||
import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.PutItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.QueryRequest;
|
||||
import javax.annotation.Nullable;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
|
||||
/**
|
||||
* A job scheduler maintains a delay queue of tasks to be run at some time in the future. Callers schedule jobs with
|
||||
* the {@link #scheduleJob(Instant, byte[])} method, and concrete subclasses actually execute jobs by implementing the
|
||||
* {@link #processJob(byte[])} method. Some entity must call {@link #processAvailableJobs()} to actually find and
|
||||
* process jobs that are ready for execution.
|
||||
*/
|
||||
public abstract class JobScheduler {
|
||||
|
||||
private final DynamoDbAsyncClient dynamoDbAsyncClient;
|
||||
private final String tableName;
|
||||
private final Duration jobExpiration;
|
||||
private final Clock clock;
|
||||
|
||||
private final Logger logger = LoggerFactory.getLogger(getClass());
|
||||
|
||||
// The name of this scheduler (DynamoDB string)
|
||||
@VisibleForTesting
|
||||
public static final String KEY_SCHEDULER_NAME = "S";
|
||||
|
||||
// The timestamp (and additional random data; please see #buildRunAtAttribute for details) for the job
|
||||
// (DynamoDB byte array)
|
||||
@VisibleForTesting
|
||||
public static final String ATTR_RUN_AT = "T";
|
||||
|
||||
// Additional application-specific data for the job (DynamoDB byte array)
|
||||
private static final String ATTR_JOB_DATA = "D";
|
||||
|
||||
// The time at which this job should be garbage-collected if not already deleted (DynamoDB number;
|
||||
// seconds from the epoch)
|
||||
private static final String ATTR_TTL = "E";
|
||||
|
||||
private static final String SCHEDULE_JOB_COUNTER_NAME = MetricsUtil.name(JobScheduler.class, "scheduleJob");
|
||||
private static final String PROCESS_JOB_COUNTER_NAME = MetricsUtil.name(JobScheduler.class, "processJob");
|
||||
|
||||
private static final String SCHEDULER_NAME_TAG = "schedulerName";
|
||||
private static final String OUTCOME_TAG = "outcome";
|
||||
|
||||
private static final int MAX_CONCURRENCY = 16;
|
||||
|
||||
protected JobScheduler(final DynamoDbAsyncClient dynamoDbAsyncClient,
|
||||
final String tableName,
|
||||
final Duration jobExpiration,
|
||||
final Clock clock) {
|
||||
|
||||
this.dynamoDbAsyncClient = dynamoDbAsyncClient;
|
||||
this.tableName = tableName;
|
||||
this.jobExpiration = jobExpiration;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the unique name of this scheduler. Scheduler names are used to "namespace" jobs.
|
||||
*
|
||||
* @return the unique name of this scheduler
|
||||
*/
|
||||
public abstract String getSchedulerName();
|
||||
|
||||
/**
|
||||
* Processes a previously-scheduled job.
|
||||
*
|
||||
* @param jobData opaque, application-specific data provided at the time the job was scheduled
|
||||
*
|
||||
* @return A future that yields a brief, human-readable status code when the job has been fully processed. On
|
||||
* successful completion, the job will be deleted. The job will not be deleted if the future completes exceptionally.
|
||||
*/
|
||||
protected abstract CompletableFuture<String> processJob(@Nullable byte[] jobData);
|
||||
|
||||
/**
|
||||
* Schedules a job to run at or after the given {@code runAt} time. Concrete implementations must override this method
|
||||
* to expose it publicly, or provide some more application-appropriate method for public callers.
|
||||
*
|
||||
* @param runAt the time at or after which to run the job
|
||||
* @param jobData application-specific data describing the job; may be {@code null}
|
||||
*
|
||||
* @return a future that completes when the job has been scheduled
|
||||
*/
|
||||
protected CompletableFuture<Void> scheduleJob(final Instant runAt, @Nullable final byte[] jobData) {
|
||||
return Mono.fromFuture(() -> scheduleJob(buildRunAtAttribute(runAt), runAt.plus(jobExpiration), jobData))
|
||||
.retryWhen(Retry.backoff(8, Duration.ofSeconds(1)).maxBackoff(Duration.ofSeconds(4)))
|
||||
.toFuture()
|
||||
.thenRun(() -> Metrics.counter(SCHEDULE_JOB_COUNTER_NAME, SCHEDULER_NAME_TAG, getSchedulerName()).increment());
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
CompletableFuture<Void> scheduleJob(final AttributeValue runAt, final Instant expiration, @Nullable final byte[] jobData) {
|
||||
final Map<String, AttributeValue> item = new HashMap<>(Map.of(
|
||||
KEY_SCHEDULER_NAME, AttributeValue.fromS(getSchedulerName()),
|
||||
ATTR_RUN_AT, runAt,
|
||||
ATTR_TTL, AttributeValue.fromN(String.valueOf(expiration.getEpochSecond()))));
|
||||
|
||||
if (jobData != null) {
|
||||
item.put(ATTR_JOB_DATA, AttributeValue.fromB(SdkBytes.fromByteArray(jobData)));
|
||||
}
|
||||
|
||||
return dynamoDbAsyncClient.putItem(PutItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.item(item)
|
||||
.conditionExpression("attribute_not_exists(#schedulerName)")
|
||||
.expressionAttributeNames(Map.of("#schedulerName", KEY_SCHEDULER_NAME))
|
||||
.build())
|
||||
.thenRun(Util.NOOP);
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds and processes all jobs whose {@code runAt} time is less than or equal to the current time. Scheduled jobs
|
||||
* will be deleted once they have been processed successfully.
|
||||
*
|
||||
* @return a future that completes when all available jobs have been processed
|
||||
*
|
||||
* @see #processJob(byte[])
|
||||
*/
|
||||
public CompletableFuture<Void> processAvailableJobs() {
|
||||
return Flux.from(dynamoDbAsyncClient.queryPaginator(QueryRequest.builder()
|
||||
.tableName(tableName)
|
||||
.keyConditionExpression("#schedulerName = :schedulerName AND #runAt <= :maxRunAt")
|
||||
.expressionAttributeNames(Map.of(
|
||||
"#schedulerName", KEY_SCHEDULER_NAME,
|
||||
"#runAt", ATTR_RUN_AT))
|
||||
.expressionAttributeValues(Map.of(
|
||||
":schedulerName", AttributeValue.fromS(getSchedulerName()),
|
||||
":maxRunAt", buildMaxRunAtAttribute(clock.instant())))
|
||||
.build())
|
||||
.items())
|
||||
.flatMap(item -> {
|
||||
final byte[] jobData = item.containsKey(ATTR_JOB_DATA)
|
||||
? item.get(ATTR_JOB_DATA).b().asByteArray()
|
||||
: null;
|
||||
|
||||
return Mono.fromFuture(processJob(jobData))
|
||||
.doOnNext(outcome -> Metrics.counter(PROCESS_JOB_COUNTER_NAME,
|
||||
SCHEDULER_NAME_TAG, getSchedulerName(),
|
||||
OUTCOME_TAG, outcome)
|
||||
.increment())
|
||||
.then(Mono.fromFuture(() -> deleteJob(item.get(KEY_SCHEDULER_NAME), item.get(ATTR_RUN_AT))))
|
||||
.onErrorResume(throwable -> {
|
||||
logger.warn("Failed to process job", throwable);
|
||||
return Mono.empty();
|
||||
});
|
||||
}, MAX_CONCURRENCY)
|
||||
.then()
|
||||
.toFuture();
|
||||
}
|
||||
|
||||
private CompletableFuture<Void> deleteJob(final AttributeValue schedulerName, final AttributeValue runAt) {
|
||||
return dynamoDbAsyncClient.deleteItem(DeleteItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.key(Map.of(
|
||||
KEY_SCHEDULER_NAME, schedulerName,
|
||||
ATTR_RUN_AT, runAt))
|
||||
.build())
|
||||
.thenRun(Util.NOOP);
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs an attribute value that contains a sort key that will be greater than any sort key generated for an
|
||||
* earlier {@code runAt} time and less than a sort key generated for a later {@code runAt} time. The returned value
|
||||
* begins with the 8-byte, big-endian representation of the given {@code runAt} time in milliseconds since the epoch
|
||||
* and ends with a random 8-byte suffix. The random suffix ensures that multiple jobs scheduled for the same
|
||||
* {@code runAt} time will have distinct primary keys; the order in which jobs scheduled at the same time will be
|
||||
* executed is also random as a result.
|
||||
*
|
||||
* @param runAt the time for which to generate a sort key
|
||||
*
|
||||
* @return a probably-unique sort key for the given {@code runAt} time
|
||||
*/
|
||||
AttributeValue buildRunAtAttribute(final Instant runAt) {
|
||||
return buildRunAtAttribute(runAt, ThreadLocalRandom.current().nextLong());
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
AttributeValue buildRunAtAttribute(final Instant runAt, final long salt) {
|
||||
return AttributeValue.fromB(SdkBytes.fromByteBuffer(ByteBuffer.allocate(24)
|
||||
.putLong(runAt.toEpochMilli())
|
||||
.putLong(clock.millis())
|
||||
.putLong(salt)
|
||||
.flip()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs a sort key value that is greater than or equal to all other sort keys for jobs with the same or earlier
|
||||
* {@code runAt} time.
|
||||
*
|
||||
* @param runAt the maximum scheduled time for jobs to match
|
||||
*
|
||||
* @return an attribute value for a sort key that is greater than or equal to the sort key for all other jobs
|
||||
* scheduled to run at or before the given {@code runAt} time
|
||||
*/
|
||||
static AttributeValue buildMaxRunAtAttribute(final Instant runAt) {
|
||||
return AttributeValue.fromB(SdkBytes.fromByteBuffer(ByteBuffer.allocate(24)
|
||||
.putLong(runAt.toEpochMilli())
|
||||
.putLong(0xfffffffffffffffL)
|
||||
.putLong(0xfffffffffffffffL)
|
||||
.flip()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package org.whispersystems.textsecuregcm.scheduler;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.i18n.phonenumbers.NumberParseException;
|
||||
import com.google.i18n.phonenumbers.PhoneNumberToTimeZonesMapper;
|
||||
import com.google.i18n.phonenumbers.PhoneNumberUtil;
|
||||
import com.google.i18n.phonenumbers.Phonenumber;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
|
||||
public class SchedulingUtil {
|
||||
|
||||
/**
|
||||
* Gets a present or future time at which to send a notification to a device associated with the given account. This
|
||||
* is mainly intended to facilitate scheduling notifications such that they arrive during a recipient's waking hours.
|
||||
* <p/>
|
||||
* This method will attempt to use a timezone derived from the account's phone number to choose an appropriate time
|
||||
* to send a notification. If a timezone cannot be derived from the account's phone number, then this method will use
|
||||
* the account's creation time as a hint. As an example, if the account was created at 07:17 in the server's local
|
||||
* time, we can assume that the account holder was awake at that time of day, and it's likely a safe time to send a
|
||||
* notification in the absence of other hints.
|
||||
*
|
||||
* @param account the account that will receive the notification
|
||||
* @param preferredTime the preferred local time (e.g. "noon") at which to deliver the notification
|
||||
* @param clock a source of the current time
|
||||
*
|
||||
* @return the next time in the present or future at which to send a notification for the target account
|
||||
*/
|
||||
public static Instant getNextRecommendedNotificationTime(final Account account,
|
||||
final LocalTime preferredTime,
|
||||
final Clock clock) {
|
||||
|
||||
final ZonedDateTime candidateNotificationTime = getZoneOffset(account, clock)
|
||||
.map(zoneOffset -> ZonedDateTime.now(zoneOffset).with(preferredTime))
|
||||
.orElseGet(() -> {
|
||||
// We couldn't find a reasonable timezone for the account for some reason, so make an educated guess at a
|
||||
// reasonable time to send a notification based on the account's creation time.
|
||||
final Instant accountCreation = Instant.ofEpochMilli(account.getPrimaryDevice().getCreated());
|
||||
final LocalTime accountCreationLocalTime = LocalTime.ofInstant(accountCreation, ZoneId.systemDefault());
|
||||
|
||||
return ZonedDateTime.now(ZoneId.systemDefault()).with(accountCreationLocalTime);
|
||||
});
|
||||
|
||||
if (candidateNotificationTime.toInstant().isBefore(clock.instant())) {
|
||||
// We've missed our opportunity today, so go for the same time tomorrow
|
||||
return candidateNotificationTime.plusDays(1).toInstant();
|
||||
} else {
|
||||
// The best time to send a notification hasn't happened yet today
|
||||
return candidateNotificationTime.toInstant();
|
||||
}
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static Optional<ZoneOffset> getZoneOffset(final Account account, final Clock clock) {
|
||||
try {
|
||||
final Phonenumber.PhoneNumber phoneNumber = PhoneNumberUtil.getInstance().parse(account.getNumber(), null);
|
||||
|
||||
final List<String> timeZonesForNumber =
|
||||
PhoneNumberToTimeZonesMapper.getInstance().getTimeZonesForNumber(phoneNumber);
|
||||
|
||||
if (timeZonesForNumber.equals(List.of(PhoneNumberToTimeZonesMapper.getUnknownTimeZone()))) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
final List<ZoneOffset> sortedZoneOffsets = timeZonesForNumber
|
||||
.stream()
|
||||
.map(id -> {
|
||||
try {
|
||||
return ZoneId.of(id);
|
||||
} catch (final Exception e) {
|
||||
return null;
|
||||
}
|
||||
})
|
||||
.filter(Objects::nonNull)
|
||||
.map(ZoneId::getRules)
|
||||
.distinct()
|
||||
.map(zoneRules -> zoneRules.getOffset(clock.instant()))
|
||||
.sorted()
|
||||
.toList();
|
||||
|
||||
return Optional.of(sortedZoneOffsets.get(sortedZoneOffsets.size() / 2));
|
||||
} catch (final NumberParseException e) {
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -1,9 +1,9 @@
|
||||
package org.whispersystems.textsecuregcm.spam;
|
||||
|
||||
import org.whispersystems.textsecuregcm.auth.AccountAndAuthenticatedDeviceHolder;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import javax.ws.rs.container.ContainerRequestContext;
|
||||
import java.util.Optional;
|
||||
import java.util.function.Function;
|
||||
|
||||
/**
|
||||
* Generates ReportSpamTokens to be used for spam reports.
|
||||
@@ -18,7 +18,7 @@ public interface ReportSpamTokenProvider {
|
||||
* @param maybeDestination the intended recepient of the message if available
|
||||
* @return either a generated token or nothing
|
||||
*/
|
||||
Optional<byte[]> makeReportSpamToken(ContainerRequestContext context, final Account sender,
|
||||
Optional<byte[]> makeReportSpamToken(ContainerRequestContext context, final AccountAndAuthenticatedDeviceHolder sender,
|
||||
final Optional<Account> maybeDestination);
|
||||
|
||||
/**
|
||||
|
||||
@@ -289,23 +289,20 @@ public class Account {
|
||||
}
|
||||
|
||||
public boolean isPaymentActivationSupported() {
|
||||
return allEnabledDevicesHaveCapability(DeviceCapabilities::paymentActivation);
|
||||
return allDevicesHaveCapability(DeviceCapabilities::paymentActivation);
|
||||
}
|
||||
|
||||
private boolean allEnabledDevicesHaveCapability(final Predicate<DeviceCapabilities> predicate) {
|
||||
public boolean isDeleteSyncSupported() {
|
||||
return allDevicesHaveCapability(DeviceCapabilities::deleteSync);
|
||||
}
|
||||
|
||||
private boolean allDevicesHaveCapability(final Predicate<DeviceCapabilities> predicate) {
|
||||
requireNotStale();
|
||||
|
||||
return devices.stream()
|
||||
.filter(Device::isEnabled)
|
||||
.allMatch(device -> device.getCapabilities() != null && predicate.test(device.getCapabilities()));
|
||||
}
|
||||
|
||||
public boolean isEnabled() {
|
||||
requireNotStale();
|
||||
|
||||
return getPrimaryDevice().isEnabled();
|
||||
}
|
||||
|
||||
public byte getNextDeviceId() {
|
||||
requireNotStale();
|
||||
|
||||
@@ -322,14 +319,6 @@ public class Account {
|
||||
return candidateId;
|
||||
}
|
||||
|
||||
public boolean hasEnabledLinkedDevice() {
|
||||
requireNotStale();
|
||||
|
||||
return devices.stream()
|
||||
.filter(d -> Device.PRIMARY_ID != d.getId())
|
||||
.anyMatch(Device::isEnabled);
|
||||
}
|
||||
|
||||
public void setIdentityKey(final IdentityKey identityKey) {
|
||||
requireNotStale();
|
||||
|
||||
@@ -500,12 +489,6 @@ public class Account {
|
||||
this.discoverableByPhoneNumber = discoverableByPhoneNumber;
|
||||
}
|
||||
|
||||
public boolean shouldBeVisibleInDirectory() {
|
||||
requireNotStale();
|
||||
|
||||
return isEnabled() && isDiscoverableByPhoneNumber();
|
||||
}
|
||||
|
||||
public int getVersion() {
|
||||
requireNotStale();
|
||||
|
||||
|
||||
@@ -443,7 +443,7 @@ public class Accounts extends AbstractDynamoDbStore {
|
||||
.expressionAttributeValues(Map.of(
|
||||
":number", numberAttr,
|
||||
":data", accountDataAttributeValue(account),
|
||||
":cds", AttributeValues.fromBool(account.shouldBeVisibleInDirectory()),
|
||||
":cds", AttributeValues.fromBool(account.isDiscoverableByPhoneNumber()),
|
||||
":pni", pniAttr,
|
||||
":version", AttributeValues.fromInt(account.getVersion()),
|
||||
":version_increment", AttributeValues.fromInt(1)))
|
||||
@@ -924,7 +924,7 @@ public class Accounts extends AbstractDynamoDbStore {
|
||||
|
||||
final Map<String, AttributeValue> attrValues = new HashMap<>(Map.of(
|
||||
":data", accountDataAttributeValue(account),
|
||||
":cds", AttributeValues.fromBool(account.shouldBeVisibleInDirectory()),
|
||||
":cds", AttributeValues.fromBool(account.isDiscoverableByPhoneNumber()),
|
||||
":version", AttributeValues.fromInt(account.getVersion()),
|
||||
":version_increment", AttributeValues.fromInt(1)));
|
||||
|
||||
@@ -1359,7 +1359,7 @@ public class Accounts extends AbstractDynamoDbStore {
|
||||
ATTR_PNI_UUID, pniUuidAttr,
|
||||
ATTR_ACCOUNT_DATA, accountDataAttributeValue(account),
|
||||
ATTR_VERSION, AttributeValues.fromInt(account.getVersion()),
|
||||
ATTR_CANONICALLY_DISCOVERABLE, AttributeValues.fromBool(account.shouldBeVisibleInDirectory())));
|
||||
ATTR_CANONICALLY_DISCOVERABLE, AttributeValues.fromBool(account.isDiscoverableByPhoneNumber())));
|
||||
|
||||
// Add the UAK if it's in the account
|
||||
account.getUnidentifiedAccessKey()
|
||||
|
||||
@@ -490,7 +490,6 @@ public class AccountsManager {
|
||||
|
||||
account.getDevices()
|
||||
.stream()
|
||||
.filter(Device::isEnabled)
|
||||
.forEach(device -> device.setPhoneNumberIdentityRegistrationId(pniRegistrationIds.get(device.getId())));
|
||||
|
||||
account.setPhoneNumberIdentityKey(pniIdentityKey);
|
||||
|
||||
+21
-19
@@ -115,8 +115,13 @@ public class ChangeNumberManager {
|
||||
}
|
||||
|
||||
private void sendDeviceMessages(final Account account, final List<IncomingMessage> deviceMessages) {
|
||||
deviceMessages.forEach(message ->
|
||||
sendMessageToSelf(account, account.getDevice(message.destinationDeviceId()), message));
|
||||
try {
|
||||
deviceMessages.forEach(message ->
|
||||
sendMessageToSelf(account, account.getDevice(message.destinationDeviceId()), message));
|
||||
} catch (RuntimeException e) {
|
||||
logger.warn("Changed number but could not send all device messages on {}", account.getUuid(), e);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
@@ -130,23 +135,20 @@ public class ChangeNumberManager {
|
||||
logger.debug("destination device not present");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
long serverTimestamp = System.currentTimeMillis();
|
||||
Envelope envelope = Envelope.newBuilder()
|
||||
.setType(Envelope.Type.forNumber(message.type()))
|
||||
.setTimestamp(serverTimestamp)
|
||||
.setServerTimestamp(serverTimestamp)
|
||||
.setDestinationUuid(new AciServiceIdentifier(sourceAndDestinationAccount.getUuid()).toServiceIdentifierString())
|
||||
.setContent(ByteString.copyFrom(contents.get()))
|
||||
.setSourceUuid(new AciServiceIdentifier(sourceAndDestinationAccount.getUuid()).toServiceIdentifierString())
|
||||
.setSourceDevice((int) Device.PRIMARY_ID)
|
||||
.setUpdatedPni(sourceAndDestinationAccount.getPhoneNumberIdentifier().toString())
|
||||
.setUrgent(true)
|
||||
.build();
|
||||
|
||||
messageSender.sendMessage(sourceAndDestinationAccount, destinationDevice.get(), envelope, false);
|
||||
} catch (NotPushRegisteredException e) {
|
||||
logger.debug("Not registered", e);
|
||||
}
|
||||
final long serverTimestamp = System.currentTimeMillis();
|
||||
final Envelope envelope = Envelope.newBuilder()
|
||||
.setType(Envelope.Type.forNumber(message.type()))
|
||||
.setTimestamp(serverTimestamp)
|
||||
.setServerTimestamp(serverTimestamp)
|
||||
.setDestinationUuid(new AciServiceIdentifier(sourceAndDestinationAccount.getUuid()).toServiceIdentifierString())
|
||||
.setContent(ByteString.copyFrom(contents.get()))
|
||||
.setSourceUuid(new AciServiceIdentifier(sourceAndDestinationAccount.getUuid()).toServiceIdentifierString())
|
||||
.setSourceDevice((int) Device.PRIMARY_ID)
|
||||
.setUpdatedPni(sourceAndDestinationAccount.getPhoneNumberIdentifier().toString())
|
||||
.setUrgent(true)
|
||||
.build();
|
||||
|
||||
messageSender.sendMessage(sourceAndDestinationAccount, destinationDevice.get(), envelope, false);
|
||||
}
|
||||
}
|
||||
@@ -11,11 +11,9 @@ import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.OptionalInt;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
import javax.annotation.Nullable;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
|
||||
import org.whispersystems.textsecuregcm.util.DeviceNameByteArrayAdapter;
|
||||
|
||||
@@ -57,9 +55,6 @@ public class Device {
|
||||
@JsonProperty
|
||||
private long pushTimestamp;
|
||||
|
||||
@JsonProperty
|
||||
private long uninstalledFeedback;
|
||||
|
||||
@JsonProperty
|
||||
private boolean fetchesMessages;
|
||||
|
||||
@@ -102,14 +97,6 @@ public class Device {
|
||||
this.voipApnId = voipApnId;
|
||||
}
|
||||
|
||||
public void setUninstalledFeedbackTimestamp(long uninstalledFeedback) {
|
||||
this.uninstalledFeedback = uninstalledFeedback;
|
||||
}
|
||||
|
||||
public long getUninstalledFeedbackTimestamp() {
|
||||
return uninstalledFeedback;
|
||||
}
|
||||
|
||||
public void setLastSeen(long lastSeen) {
|
||||
this.lastSeen = lastSeen;
|
||||
}
|
||||
@@ -199,12 +186,6 @@ public class Device {
|
||||
this.capabilities = capabilities;
|
||||
}
|
||||
|
||||
public boolean isEnabled() {
|
||||
boolean hasChannel = fetchesMessages || StringUtils.isNotEmpty(getApnId()) || StringUtils.isNotEmpty(getGcmId());
|
||||
|
||||
return (id == PRIMARY_ID && hasChannel) || (id != PRIMARY_ID && hasChannel && !isExpired());
|
||||
}
|
||||
|
||||
public boolean isExpired() {
|
||||
return isPrimary()
|
||||
? lastSeen < (System.currentTimeMillis() - ALLOWED_PRIMARY_IDLE_MILLIS)
|
||||
@@ -251,6 +232,6 @@ public class Device {
|
||||
return this.userAgent;
|
||||
}
|
||||
|
||||
public record DeviceCapabilities(boolean storage, boolean transfer, boolean paymentActivation) {
|
||||
public record DeviceCapabilities(boolean storage, boolean transfer, boolean paymentActivation, boolean deleteSync) {
|
||||
}
|
||||
}
|
||||
+16
-5
@@ -22,6 +22,7 @@ import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
@@ -161,8 +162,13 @@ public class MessagePersister implements Managed {
|
||||
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(), deviceId);
|
||||
persistQueue(maybeAccount.get(), maybeDevice.get());
|
||||
} catch (final Exception e) {
|
||||
persistQueueExceptionMeter.increment();
|
||||
logger.warn("Failed to persist queue {}::{}; will schedule for retry", accountUuid, deviceId, e);
|
||||
@@ -180,8 +186,9 @@ public class MessagePersister implements Managed {
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
void persistQueue(final Account account, final byte deviceId) throws MessagePersistenceException {
|
||||
void persistQueue(final Account account, final Device device) throws MessagePersistenceException {
|
||||
final UUID accountUuid = account.getUuid();
|
||||
final byte deviceId = device.getId();
|
||||
|
||||
final Timer.Sample sample = Timer.start();
|
||||
|
||||
@@ -196,7 +203,7 @@ public class MessagePersister implements Managed {
|
||||
do {
|
||||
messages = messagesCache.getMessagesToPersist(accountUuid, deviceId, MESSAGE_BATCH_LIMIT);
|
||||
|
||||
int messagesRemovedFromCache = messagesManager.persistMessages(accountUuid, deviceId, messages);
|
||||
int messagesRemovedFromCache = messagesManager.persistMessages(accountUuid, device, messages);
|
||||
messageCount += messages.size();
|
||||
|
||||
if (messagesRemovedFromCache == 0) {
|
||||
@@ -239,14 +246,14 @@ public class MessagePersister implements Managed {
|
||||
// its messages) is unlinked
|
||||
final Device deviceToDelete = account.getDevices()
|
||||
.stream()
|
||||
.filter(d -> !d.isPrimary() && !d.isEnabled())
|
||||
.filter(d -> !d.isPrimary() && !deviceHasMessageDeliveryChannel(d))
|
||||
.min(Comparator.comparing(Device::getLastSeen))
|
||||
.or(() ->
|
||||
Flux.fromIterable(account.getDevices())
|
||||
.filter(d -> !d.isPrimary())
|
||||
.flatMap(d ->
|
||||
messagesManager
|
||||
.getEarliestUndeliveredTimestampForDevice(account.getUuid(), d.getId())
|
||||
.getEarliestUndeliveredTimestampForDevice(account.getUuid(), d)
|
||||
.map(t -> Tuples.of(d, t)))
|
||||
.sort(Comparator.comparing(Tuple2::getT2))
|
||||
.map(Tuple2::getT1)
|
||||
@@ -282,4 +289,8 @@ public class MessagePersister implements Managed {
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static boolean deviceHasMessageDeliveryChannel(final Device device) {
|
||||
return device.getFetchesMessages() || StringUtils.isNotEmpty(device.getApnId()) || StringUtils.isNotEmpty(device.getGcmId());
|
||||
}
|
||||
}
|
||||
@@ -213,6 +213,13 @@ public class MessagesCache extends RedisClusterPubSubAdapter<String, String> imp
|
||||
connection -> connection.sync().zcard(getMessageQueueKey(destinationUuid, destinationDevice)) > 0);
|
||||
}
|
||||
|
||||
public CompletableFuture<Boolean> hasMessagesAsync(final UUID destinationUuid, final byte destinationDevice) {
|
||||
return redisCluster.withBinaryCluster(connection ->
|
||||
connection.async().zcard(getMessageQueueKey(destinationUuid, destinationDevice))
|
||||
.thenApply(cardinality -> cardinality > 0))
|
||||
.toCompletableFuture();
|
||||
}
|
||||
|
||||
public Publisher<MessageProtos.Envelope> get(final UUID destinationUuid, final byte destinationDevice) {
|
||||
|
||||
final long earliestAllowableEphemeralTimestamp =
|
||||
|
||||
+83
-95
@@ -11,6 +11,9 @@ import static io.micrometer.core.instrument.Metrics.timer;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.common.collect.ImmutableMap;
|
||||
import com.google.protobuf.InvalidProtocolBufferException;
|
||||
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.time.Duration;
|
||||
@@ -23,6 +26,8 @@ import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.reactivestreams.Publisher;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
@@ -32,6 +37,8 @@ import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
import reactor.core.scheduler.Schedulers;
|
||||
import reactor.util.function.Tuples;
|
||||
import reactor.util.function.Tuple2;
|
||||
import software.amazon.awssdk.core.SdkBytes;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
|
||||
@@ -84,24 +91,24 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
|
||||
}
|
||||
|
||||
public void store(final List<MessageProtos.Envelope> messages, final UUID destinationAccountUuid,
|
||||
final byte destinationDeviceId) {
|
||||
storeTimer.record(() -> writeInBatches(messages, (messageBatch) -> storeBatch(messageBatch, destinationAccountUuid, destinationDeviceId)));
|
||||
final Device destinationDevice) {
|
||||
storeTimer.record(() -> writeInBatches(messages, (messageBatch) -> storeBatch(messageBatch, destinationAccountUuid, destinationDevice)));
|
||||
}
|
||||
|
||||
private void storeBatch(final List<MessageProtos.Envelope> messages, final UUID destinationAccountUuid,
|
||||
final byte destinationDeviceId) {
|
||||
final Device destinationDevice) {
|
||||
if (messages.size() > DYNAMO_DB_MAX_BATCH_SIZE) {
|
||||
throw new IllegalArgumentException("Maximum batch size of " + DYNAMO_DB_MAX_BATCH_SIZE + " exceeded with " + messages.size() + " messages");
|
||||
}
|
||||
|
||||
final AttributeValue partitionKey = convertPartitionKey(destinationAccountUuid);
|
||||
final AttributeValue partitionKey = convertPartitionKey(destinationAccountUuid, destinationDevice);
|
||||
List<WriteRequest> writeItems = new ArrayList<>();
|
||||
for (MessageProtos.Envelope message : messages) {
|
||||
final UUID messageUuid = UUID.fromString(message.getServerGuid());
|
||||
|
||||
final ImmutableMap.Builder<String, AttributeValue> item = ImmutableMap.<String, AttributeValue>builder()
|
||||
.put(KEY_PARTITION, partitionKey)
|
||||
.put(KEY_SORT, convertSortKey(destinationDeviceId, message.getServerTimestamp(), messageUuid))
|
||||
.put(KEY_SORT, convertSortKey(destinationDevice.getId(), message.getServerTimestamp(), messageUuid))
|
||||
.put(LOCAL_INDEX_MESSAGE_UUID_KEY_SORT, convertLocalIndexMessageUuidSortKey(messageUuid))
|
||||
.put(KEY_TTL, AttributeValues.fromLong(getTtlForMessage(message)))
|
||||
.put(KEY_ENVELOPE_BYTES, AttributeValue.builder().b(SdkBytes.fromByteArray(message.toByteArray())).build());
|
||||
@@ -114,20 +121,36 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
|
||||
executeTableWriteItemsUntilComplete(Map.of(tableName, writeItems));
|
||||
}
|
||||
|
||||
public Publisher<MessageProtos.Envelope> load(final UUID destinationAccountUuid, final byte destinationDeviceId,
|
||||
final Integer limit) {
|
||||
public CompletableFuture<Boolean> mayHaveMessages(final UUID accountIdentifier, final Device device) {
|
||||
final AttributeValue partitionKey = convertPartitionKey(accountIdentifier, device);
|
||||
|
||||
final AttributeValue partitionKey = convertPartitionKey(destinationAccountUuid);
|
||||
final QueryRequest.Builder queryRequestBuilder = QueryRequest.builder()
|
||||
QueryRequest.Builder queryRequestBuilder = QueryRequest.builder()
|
||||
.tableName(tableName)
|
||||
.consistentRead(false)
|
||||
.limit(1)
|
||||
.keyConditionExpression("#part = :part")
|
||||
.expressionAttributeNames(Map.of("#part", KEY_PARTITION))
|
||||
.expressionAttributeValues(Map.of(":part", partitionKey));
|
||||
|
||||
return dbAsyncClient.query(queryRequestBuilder.build())
|
||||
.thenApply(queryResponse -> queryResponse.count() > 0);
|
||||
}
|
||||
|
||||
public Publisher<MessageProtos.Envelope> load(final UUID destinationAccountUuid, final Device device, final Integer limit) {
|
||||
return Flux.concat(
|
||||
Stream.of(convertPartitionKeyDeprecated(destinationAccountUuid, device), convertPartitionKey(destinationAccountUuid, device))
|
||||
.distinct()
|
||||
.map(pk -> load(limit, pk))
|
||||
.toList());
|
||||
}
|
||||
|
||||
public Publisher<MessageProtos.Envelope> load(final Integer limit, final AttributeValue partitionKey) {
|
||||
QueryRequest.Builder queryRequestBuilder = QueryRequest.builder()
|
||||
.tableName(tableName)
|
||||
.consistentRead(true)
|
||||
.keyConditionExpression("#part = :part AND begins_with ( #sort , :sortprefix )")
|
||||
.expressionAttributeNames(Map.of(
|
||||
"#part", KEY_PARTITION,
|
||||
"#sort", KEY_SORT))
|
||||
.expressionAttributeValues(Map.of(
|
||||
":part", partitionKey,
|
||||
":sortprefix", convertDestinationDeviceIdToSortKeyPrefix(destinationDeviceId)));
|
||||
.keyConditionExpression("#part = :part")
|
||||
.expressionAttributeNames(Map.of("#part", KEY_PARTITION))
|
||||
.expressionAttributeValues(Map.of(":part", partitionKey));
|
||||
|
||||
if (limit != null) {
|
||||
// some callers don’t take advantage of reactive streams, so we want to support limiting the fetch size. Otherwise,
|
||||
@@ -150,9 +173,20 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
|
||||
}
|
||||
|
||||
public CompletableFuture<Optional<MessageProtos.Envelope>> deleteMessageByDestinationAndGuid(
|
||||
final UUID destinationAccountUuid, final UUID messageUuid) {
|
||||
final UUID destinationAccountUuid, final Device destinationDevice, final UUID messageUuid) {
|
||||
return Stream.of(convertPartitionKey(destinationAccountUuid, destinationDevice),
|
||||
convertPartitionKeyDeprecated(destinationAccountUuid, destinationDevice))
|
||||
.distinct()
|
||||
.map(pk -> deleteMessageByDestinationAndGuid(pk, messageUuid))
|
||||
// this combines the futures by producing a future that returns an arbitrary nonempty
|
||||
// result if there is one, which should be OK because only one of the keys
|
||||
// should produce a nonempty result for any given message uuid
|
||||
.reduce((f, g) -> f.thenCombine(g, (a, b) -> a.or(() -> b)))
|
||||
.get();
|
||||
}
|
||||
|
||||
final AttributeValue partitionKey = convertPartitionKey(destinationAccountUuid);
|
||||
public CompletableFuture<Optional<MessageProtos.Envelope>> deleteMessageByDestinationAndGuid(
|
||||
final AttributeValue partitionKey, final UUID messageUuid) {
|
||||
final QueryRequest queryRequest = QueryRequest.builder()
|
||||
.tableName(tableName)
|
||||
.indexName(LOCAL_INDEX_MESSAGE_UUID_NAME)
|
||||
@@ -193,10 +227,20 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
|
||||
}
|
||||
|
||||
public CompletableFuture<Optional<MessageProtos.Envelope>> deleteMessage(final UUID destinationAccountUuid,
|
||||
final byte destinationDeviceId, final UUID messageUuid, final long serverTimestamp) {
|
||||
final Device destinationDevice, final UUID messageUuid, final long serverTimestamp) {
|
||||
return Stream.of(convertPartitionKey(destinationAccountUuid, destinationDevice),
|
||||
convertPartitionKeyDeprecated(destinationAccountUuid, destinationDevice))
|
||||
.distinct()
|
||||
.map(pk -> deleteMessage(pk, destinationDevice, messageUuid, serverTimestamp))
|
||||
// this combines the futures by producing a future that returns an arbitrary nonempty
|
||||
// result if there is one, which should be OK because only one of the keys
|
||||
// should produce a nonempty result for any given message uuid
|
||||
.reduce((f, g) -> f.thenCombine(g, (a, b) -> a.or(() -> b)))
|
||||
.get();
|
||||
}
|
||||
|
||||
final AttributeValue partitionKey = convertPartitionKey(destinationAccountUuid);
|
||||
final AttributeValue sortKey = convertSortKey(destinationDeviceId, serverTimestamp, messageUuid);
|
||||
public CompletableFuture<Optional<MessageProtos.Envelope>> deleteMessage(final AttributeValue partitionKey, final Device destinationDevice, final UUID messageUuid, final long serverTimestamp) {
|
||||
final AttributeValue sortKey = convertSortKey(destinationDevice.getId(), serverTimestamp, messageUuid);
|
||||
DeleteItemRequest.Builder deleteItemRequest = DeleteItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.key(Map.of(KEY_PARTITION, partitionKey, KEY_SORT, sortKey))
|
||||
@@ -216,64 +260,6 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
|
||||
}, messageDeletionExecutor);
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> deleteAllMessagesForAccount(final UUID destinationAccountUuid) {
|
||||
final Timer.Sample sample = Timer.start();
|
||||
|
||||
final AttributeValue partitionKey = convertPartitionKey(destinationAccountUuid);
|
||||
|
||||
return Flux.from(dbAsyncClient.queryPaginator(QueryRequest.builder()
|
||||
.tableName(tableName)
|
||||
.projectionExpression(KEY_SORT)
|
||||
.consistentRead(true)
|
||||
.keyConditionExpression("#part = :part")
|
||||
.expressionAttributeNames(Map.of("#part", KEY_PARTITION))
|
||||
.expressionAttributeValues(Map.of(":part", partitionKey))
|
||||
.build())
|
||||
.items())
|
||||
.flatMap(item -> Mono.fromFuture(() -> dbAsyncClient.deleteItem(DeleteItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.key(Map.of(
|
||||
KEY_PARTITION, partitionKey,
|
||||
KEY_SORT, item.get(KEY_SORT)))
|
||||
.build())),
|
||||
DYNAMO_DB_MAX_BATCH_SIZE)
|
||||
.then()
|
||||
.doOnSuccess(ignored -> sample.stop(timer(DELETE_BY_ACCOUNT_TIMER_NAME, "outcome", "success")))
|
||||
.doOnError(ignored -> sample.stop(timer(DELETE_BY_ACCOUNT_TIMER_NAME, "outcome", "error")))
|
||||
.toFuture();
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> deleteAllMessagesForDevice(final UUID destinationAccountUuid,
|
||||
final byte destinationDeviceId) {
|
||||
final Timer.Sample sample = Timer.start();
|
||||
final AttributeValue partitionKey = convertPartitionKey(destinationAccountUuid);
|
||||
|
||||
return Flux.from(dbAsyncClient.queryPaginator(QueryRequest.builder()
|
||||
.tableName(tableName)
|
||||
.keyConditionExpression("#part = :part AND begins_with ( #sort , :sortprefix )")
|
||||
.expressionAttributeNames(Map.of(
|
||||
"#part", KEY_PARTITION,
|
||||
"#sort", KEY_SORT))
|
||||
.expressionAttributeValues(Map.of(
|
||||
":part", partitionKey,
|
||||
":sortprefix", convertDestinationDeviceIdToSortKeyPrefix(destinationDeviceId)))
|
||||
.projectionExpression(KEY_SORT)
|
||||
.consistentRead(true)
|
||||
.build())
|
||||
.items())
|
||||
.flatMap(item -> Mono.fromFuture(() -> dbAsyncClient.deleteItem(DeleteItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.key(Map.of(
|
||||
KEY_PARTITION, partitionKey,
|
||||
KEY_SORT, item.get(KEY_SORT)))
|
||||
.build())),
|
||||
DYNAMO_DB_MAX_BATCH_SIZE)
|
||||
.then()
|
||||
.doOnSuccess(ignored -> sample.stop(timer(DELETE_BY_DEVICE_TIMER_NAME, "outcome", "success")))
|
||||
.doOnError(ignored -> sample.stop(timer(DELETE_BY_DEVICE_TIMER_NAME, "outcome", "error")))
|
||||
.toFuture();
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static MessageProtos.Envelope convertItemToEnvelope(final Map<String, AttributeValue> item)
|
||||
throws InvalidProtocolBufferException {
|
||||
@@ -285,25 +271,27 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
|
||||
return message.getServerTimestamp() / 1000 + timeToLive.getSeconds();
|
||||
}
|
||||
|
||||
private static AttributeValue convertPartitionKey(final UUID destinationAccountUuid) {
|
||||
return AttributeValues.fromUUID(destinationAccountUuid);
|
||||
}
|
||||
|
||||
private static AttributeValue convertSortKey(final byte destinationDeviceId, final long serverTimestamp,
|
||||
final UUID messageUuid) {
|
||||
ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[32]);
|
||||
// for compatibility - destinationDeviceId was previously `long`
|
||||
byteBuffer.putLong(destinationDeviceId);
|
||||
byteBuffer.putLong(serverTimestamp);
|
||||
byteBuffer.putLong(messageUuid.getMostSignificantBits());
|
||||
byteBuffer.putLong(messageUuid.getLeastSignificantBits());
|
||||
private static AttributeValue convertPartitionKey(final UUID destinationAccountUuid, final Device destinationDevice) {
|
||||
final ByteBuffer byteBuffer = ByteBuffer.allocate(24);
|
||||
byteBuffer.putLong(destinationAccountUuid.getMostSignificantBits());
|
||||
byteBuffer.putLong(destinationAccountUuid.getLeastSignificantBits());
|
||||
byteBuffer.putLong((destinationDevice.getCreated() & ~0x7f) + destinationDevice.getId());
|
||||
return AttributeValues.fromByteBuffer(byteBuffer.flip());
|
||||
}
|
||||
|
||||
private static AttributeValue convertDestinationDeviceIdToSortKeyPrefix(final byte destinationDeviceId) {
|
||||
ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[8]);
|
||||
// for compatibility - destinationDeviceId was previously `long`
|
||||
byteBuffer.putLong(destinationDeviceId);
|
||||
private static AttributeValue convertPartitionKeyDeprecated(final UUID destinationAccountUuid, final Device destinationDevice) {
|
||||
final ByteBuffer byteBuffer = ByteBuffer.allocate(24);
|
||||
byteBuffer.putLong(destinationAccountUuid.getMostSignificantBits());
|
||||
byteBuffer.putLong(destinationAccountUuid.getLeastSignificantBits());
|
||||
byteBuffer.putLong(destinationDevice.getCreated() & ~0x7f + destinationDevice.getId());
|
||||
return AttributeValues.fromByteBuffer(byteBuffer.flip());
|
||||
}
|
||||
|
||||
private static AttributeValue convertSortKey(final byte destinationDeviceId, final long serverTimestamp, final UUID messageUuid) {
|
||||
final ByteBuffer byteBuffer = ByteBuffer.allocate(24);
|
||||
byteBuffer.putLong(serverTimestamp);
|
||||
byteBuffer.putLong(messageUuid.getMostSignificantBits());
|
||||
byteBuffer.putLong(messageUuid.getLeastSignificantBits());
|
||||
return AttributeValues.fromByteBuffer(byteBuffer.flip());
|
||||
}
|
||||
|
||||
|
||||
+21
-18
@@ -63,11 +63,18 @@ public class MessagesManager {
|
||||
}
|
||||
}
|
||||
|
||||
public CompletableFuture<Boolean> mayHaveMessages(final UUID destinationUuid, final Device destinationDevice) {
|
||||
return messagesCache.hasMessagesAsync(destinationUuid, destinationDevice.getId())
|
||||
.thenCompose(hasMessages -> hasMessages
|
||||
? CompletableFuture.completedFuture(true)
|
||||
: messagesDynamoDb.mayHaveMessages(destinationUuid, destinationDevice));
|
||||
}
|
||||
|
||||
public boolean hasCachedMessages(final UUID destinationUuid, final byte destinationDevice) {
|
||||
return messagesCache.hasMessages(destinationUuid, destinationDevice);
|
||||
}
|
||||
|
||||
public Mono<Pair<List<Envelope>, Boolean>> getMessagesForDevice(UUID destinationUuid, byte destinationDevice,
|
||||
public Mono<Pair<List<Envelope>, Boolean>> getMessagesForDevice(UUID destinationUuid, Device destinationDevice,
|
||||
boolean cachedMessagesOnly) {
|
||||
|
||||
return Flux.from(
|
||||
@@ -77,43 +84,39 @@ public class MessagesManager {
|
||||
.map(envelopes -> new Pair<>(envelopes, envelopes.size() >= RESULT_SET_CHUNK_SIZE));
|
||||
}
|
||||
|
||||
public Publisher<Envelope> getMessagesForDeviceReactive(UUID destinationUuid, byte destinationDevice,
|
||||
public Publisher<Envelope> getMessagesForDeviceReactive(UUID destinationUuid, Device destinationDevice,
|
||||
final boolean cachedMessagesOnly) {
|
||||
|
||||
return getMessagesForDevice(destinationUuid, destinationDevice, null, cachedMessagesOnly);
|
||||
}
|
||||
|
||||
private Publisher<Envelope> getMessagesForDevice(UUID destinationUuid, byte destinationDevice,
|
||||
private Publisher<Envelope> getMessagesForDevice(UUID destinationUuid, Device destinationDevice,
|
||||
@Nullable Integer limit, final boolean cachedMessagesOnly) {
|
||||
|
||||
final Publisher<Envelope> dynamoPublisher =
|
||||
cachedMessagesOnly ? Flux.empty() : messagesDynamoDb.load(destinationUuid, destinationDevice, limit);
|
||||
final Publisher<Envelope> cachePublisher = messagesCache.get(destinationUuid, destinationDevice);
|
||||
final Publisher<Envelope> cachePublisher = messagesCache.get(destinationUuid, destinationDevice.getId());
|
||||
|
||||
return Flux.concat(dynamoPublisher, cachePublisher)
|
||||
.name(GET_MESSAGES_FOR_DEVICE_FLUX_NAME)
|
||||
.tap(Micrometer.metrics(Metrics.globalRegistry));
|
||||
}
|
||||
|
||||
public Mono<Long> getEarliestUndeliveredTimestampForDevice(UUID destinationUuid, byte destinationDevice) {
|
||||
public Mono<Long> getEarliestUndeliveredTimestampForDevice(UUID destinationUuid, Device destinationDevice) {
|
||||
return Mono.from(messagesDynamoDb.load(destinationUuid, destinationDevice, 1)).map(Envelope::getServerTimestamp);
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> clear(UUID destinationUuid) {
|
||||
return CompletableFuture.allOf(
|
||||
messagesCache.clear(destinationUuid),
|
||||
messagesDynamoDb.deleteAllMessagesForAccount(destinationUuid));
|
||||
return messagesCache.clear(destinationUuid);
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> clear(UUID destinationUuid, byte deviceId) {
|
||||
return CompletableFuture.allOf(
|
||||
messagesCache.clear(destinationUuid, deviceId),
|
||||
messagesDynamoDb.deleteAllMessagesForDevice(destinationUuid, deviceId));
|
||||
return messagesCache.clear(destinationUuid, deviceId);
|
||||
}
|
||||
|
||||
public CompletableFuture<Optional<Envelope>> delete(UUID destinationUuid, byte destinationDeviceId, UUID guid,
|
||||
public CompletableFuture<Optional<Envelope>> delete(UUID destinationUuid, Device destinationDevice, UUID guid,
|
||||
@Nullable Long serverTimestamp) {
|
||||
return messagesCache.remove(destinationUuid, destinationDeviceId, guid)
|
||||
return messagesCache.remove(destinationUuid, destinationDevice.getId(), guid)
|
||||
.thenComposeAsync(removed -> {
|
||||
|
||||
if (removed.isPresent()) {
|
||||
@@ -121,9 +124,9 @@ public class MessagesManager {
|
||||
}
|
||||
|
||||
if (serverTimestamp == null) {
|
||||
return messagesDynamoDb.deleteMessageByDestinationAndGuid(destinationUuid, guid);
|
||||
return messagesDynamoDb.deleteMessageByDestinationAndGuid(destinationUuid, destinationDevice, guid);
|
||||
} else {
|
||||
return messagesDynamoDb.deleteMessage(destinationUuid, destinationDeviceId, guid, serverTimestamp);
|
||||
return messagesDynamoDb.deleteMessage(destinationUuid, destinationDevice, guid, serverTimestamp);
|
||||
}
|
||||
|
||||
}, messageDeletionExecutor);
|
||||
@@ -134,20 +137,20 @@ public class MessagesManager {
|
||||
*/
|
||||
public int persistMessages(
|
||||
final UUID destinationUuid,
|
||||
final byte destinationDeviceId,
|
||||
final Device destinationDevice,
|
||||
final List<Envelope> messages) {
|
||||
|
||||
final List<Envelope> nonEphemeralMessages = messages.stream()
|
||||
.filter(envelope -> !envelope.getEphemeral())
|
||||
.collect(Collectors.toList());
|
||||
|
||||
messagesDynamoDb.store(nonEphemeralMessages, destinationUuid, destinationDeviceId);
|
||||
messagesDynamoDb.store(nonEphemeralMessages, destinationUuid, destinationDevice);
|
||||
|
||||
final List<UUID> messageGuids = messages.stream().map(message -> UUID.fromString(message.getServerGuid()))
|
||||
.collect(Collectors.toList());
|
||||
int messagesRemovedFromCache = 0;
|
||||
try {
|
||||
messagesRemovedFromCache = messagesCache.remove(destinationUuid, destinationDeviceId, messageGuids)
|
||||
messagesRemovedFromCache = messagesCache.remove(destinationUuid, destinationDevice.getId(), messageGuids)
|
||||
.get(30, TimeUnit.SECONDS).size();
|
||||
PERSIST_MESSAGE_COUNTER.increment(nonEphemeralMessages.size());
|
||||
|
||||
|
||||
-1
@@ -89,7 +89,6 @@ public class DestinationDeviceValidator {
|
||||
final Set<Byte> excludedDeviceIds) throws MismatchedDevicesException {
|
||||
|
||||
final Set<Byte> accountDeviceIds = account.getDevices().stream()
|
||||
.filter(Device::isEnabled)
|
||||
.map(Device::getId)
|
||||
.filter(deviceId -> !excludedDeviceIds.contains(deviceId))
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
@@ -14,18 +14,11 @@ import com.fasterxml.jackson.databind.JsonSerializer;
|
||||
import com.fasterxml.jackson.databind.SerializerProvider;
|
||||
import java.io.IOException;
|
||||
import java.util.Base64;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.signal.libsignal.protocol.InvalidKeyException;
|
||||
import org.signal.libsignal.protocol.ecc.ECPublicKey;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
|
||||
public class IdentityKeyAdapter {
|
||||
|
||||
private static final Counter IDENTITY_KEY_WITHOUT_VERSION_BYTE_COUNTER =
|
||||
Metrics.counter(MetricsUtil.name(IdentityKeyAdapter.class, "identityKeyWithoutVersionByte"));
|
||||
|
||||
public static class Serializer extends JsonSerializer<IdentityKey> {
|
||||
|
||||
@Override
|
||||
@@ -56,11 +49,6 @@ public class IdentityKeyAdapter {
|
||||
try {
|
||||
return new IdentityKey(identityKeyBytes);
|
||||
} catch (final InvalidKeyException e) {
|
||||
if (identityKeyBytes.length == ECPublicKey.KEY_SIZE - 1) {
|
||||
IDENTITY_KEY_WITHOUT_VERSION_BYTE_COUNTER.increment();
|
||||
return new IdentityKey(ECPublicKey.fromPublicKeyBytes(identityKeyBytes));
|
||||
}
|
||||
|
||||
throw new JsonParseException(parser, "Could not interpret identity key bytes as an EC public key", e);
|
||||
}
|
||||
}
|
||||
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package org.whispersystems.textsecuregcm.util.logging;
|
||||
|
||||
import ch.qos.logback.classic.spi.ILoggingEvent;
|
||||
import ch.qos.logback.core.filter.Filter;
|
||||
import ch.qos.logback.core.spi.FilterReply;
|
||||
|
||||
/**
|
||||
* Filters spurious warnings about setting a very specific channel option on local channels.
|
||||
* <p/>
|
||||
* gRPC unconditionally tries to set the {@code SO_KEEPALIVE} option on all of its channels, but local channels, which
|
||||
* are used by the Noise-over-WebSocket tunnel, do not support {@code SO_KEEPALIVE} and log a warning on each new
|
||||
* channel. We don't want to filter <em>all</em> warnings from the relevant logger, and so this custom filter denies
|
||||
* attempts to log the specific spurious message.
|
||||
*/
|
||||
public class UnknownKeepaliveOptionFilter extends Filter<ILoggingEvent> {
|
||||
|
||||
private static final String MESSAGE_PREFIX = "Unknown channel option 'SO_KEEPALIVE'";
|
||||
|
||||
@Override
|
||||
public FilterReply decide(final ILoggingEvent event) {
|
||||
final boolean loggerNameMatches = "io.netty.bootstrap.Bootstrap".equals(event.getLoggerName()) ||
|
||||
"io.netty.bootstrap.ServerBootstrap".equals(event.getLoggerName());
|
||||
|
||||
return loggerNameMatches && event.getMessage().startsWith(MESSAGE_PREFIX) ? FilterReply.DENY : FilterReply.NEUTRAL;
|
||||
}
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package org.whispersystems.textsecuregcm.util.logging;
|
||||
|
||||
import ch.qos.logback.classic.spi.ILoggingEvent;
|
||||
import ch.qos.logback.core.filter.Filter;
|
||||
import com.fasterxml.jackson.annotation.JsonTypeName;
|
||||
import io.dropwizard.logging.common.filter.FilterFactory;
|
||||
|
||||
@JsonTypeName("unknownKeepaliveOption")
|
||||
public class UnknownKeepaliveOptionFilterFactory implements FilterFactory<ILoggingEvent> {
|
||||
|
||||
@Override
|
||||
public Filter<ILoggingEvent> build() {
|
||||
return new UnknownKeepaliveOptionFilter();
|
||||
}
|
||||
}
|
||||
+9
-5
@@ -222,18 +222,22 @@ public class WebSocketConnection implements MessageAvailabilityListener, Displac
|
||||
if (throwable != null) {
|
||||
sendFailuresCounter.increment();
|
||||
} else {
|
||||
messageMetrics.measureOutgoingMessageLatency(message.getServerTimestamp(), "websocket", client.getUserAgent(), clientReleaseManager);
|
||||
messageMetrics.measureOutgoingMessageLatency(message.getServerTimestamp(),
|
||||
"websocket",
|
||||
device.isPrimary(),
|
||||
client.getUserAgent(),
|
||||
clientReleaseManager);
|
||||
}
|
||||
}).thenCompose(response -> {
|
||||
final CompletableFuture<Void> result;
|
||||
if (isSuccessResponse(response)) {
|
||||
|
||||
result = messagesManager.delete(auth.getAccount().getUuid(), device.getId(),
|
||||
result = messagesManager.delete(auth.getAccount().getUuid(), device,
|
||||
storedMessageInfo.guid(), storedMessageInfo.serverTimestamp())
|
||||
.thenApply(ignored -> null);
|
||||
|
||||
if (message.getType() != Envelope.Type.SERVER_DELIVERY_RECEIPT) {
|
||||
recordMessageDeliveryDuration(message.getTimestamp(), device);
|
||||
recordMessageDeliveryDuration(message.getServerTimestamp(), device);
|
||||
sendDeliveryReceiptFor(message);
|
||||
}
|
||||
} else {
|
||||
@@ -355,7 +359,7 @@ public class WebSocketConnection implements MessageAvailabilityListener, Displac
|
||||
private void sendMessages(final boolean cachedMessagesOnly, final CompletableFuture<Void> queueCleared) {
|
||||
|
||||
final Publisher<Envelope> messages =
|
||||
messagesManager.getMessagesForDeviceReactive(auth.getAccount().getUuid(), device.getId(), cachedMessagesOnly);
|
||||
messagesManager.getMessagesForDeviceReactive(auth.getAccount().getUuid(), device, cachedMessagesOnly);
|
||||
|
||||
final AtomicBoolean hasErrored = new AtomicBoolean();
|
||||
|
||||
@@ -414,7 +418,7 @@ public class WebSocketConnection implements MessageAvailabilityListener, Displac
|
||||
final UUID messageGuid = UUID.fromString(envelope.getServerGuid());
|
||||
|
||||
if (envelope.getStory() && !client.shouldDeliverStories()) {
|
||||
messagesManager.delete(auth.getAccount().getUuid(), device.getId(), messageGuid, envelope.getServerTimestamp());
|
||||
messagesManager.delete(auth.getAccount().getUuid(), device, messageGuid, envelope.getServerTimestamp());
|
||||
|
||||
return CompletableFuture.completedFuture(null);
|
||||
} else {
|
||||
|
||||
+34
-6
@@ -5,6 +5,7 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.workers;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import io.dropwizard.core.cli.Command;
|
||||
import io.dropwizard.core.setup.Bootstrap;
|
||||
import java.nio.file.Files;
|
||||
@@ -35,6 +36,25 @@ public class CheckDynamicConfigurationCommand extends Command {
|
||||
.setDefault(DynamicConfiguration.class.getCanonicalName());
|
||||
}
|
||||
|
||||
private boolean isValid(final Class<?> configurationClass, final String yamlConfig) {
|
||||
try {
|
||||
return DynamicConfigurationManager.parseConfiguration(yamlConfig, configurationClass).isPresent();
|
||||
} catch (JsonProcessingException e) {
|
||||
System.err.println(e.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Throw to exit the command cleanly but with a non-zero exit code
|
||||
*/
|
||||
private static class CommandFailedException extends RuntimeException {
|
||||
@Override
|
||||
public synchronized Throwable fillInStackTrace() {
|
||||
return this;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run(final Bootstrap<?> bootstrap, final Namespace namespace) throws Exception {
|
||||
final Path path = Path.of(namespace.getString("file"));
|
||||
@@ -53,12 +73,20 @@ public class CheckDynamicConfigurationCommand extends Command {
|
||||
configurationClasses = List.of(Class.forName(namespace.getString("class")));
|
||||
}
|
||||
|
||||
for (final Class<?> configurationClass : configurationClasses) {
|
||||
if (DynamicConfigurationManager.parseConfiguration(Files.readString(path), configurationClass).isPresent()) {
|
||||
System.out.println(configurationClass.getSimpleName() + ": dynamic configuration file at " + path + " is valid");
|
||||
} else {
|
||||
System.err.println(configurationClass.getSimpleName() + ": dynamic configuration file at " + path + " is not valid");
|
||||
}
|
||||
final String yamlConfig = Files.readString(path);
|
||||
final boolean allValid = configurationClasses.stream()
|
||||
.allMatch(cls -> {
|
||||
final boolean valid = isValid(cls, yamlConfig);
|
||||
if (valid) {
|
||||
System.out.println(cls.getSimpleName() + ": dynamic configuration file at " + path + " is valid");
|
||||
} else {
|
||||
System.err.println(cls.getSimpleName() + ": dynamic configuration file at " + path + " is not valid");
|
||||
}
|
||||
return valid;
|
||||
});
|
||||
|
||||
if (!allValid) {
|
||||
throw new CommandFailedException();
|
||||
}
|
||||
}
|
||||
}
|
||||
-3
@@ -29,7 +29,6 @@ import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfigurati
|
||||
import org.whispersystems.textsecuregcm.controllers.SecureStorageController;
|
||||
import org.whispersystems.textsecuregcm.controllers.SecureValueRecovery2Controller;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
|
||||
@@ -91,8 +90,6 @@ record CommandDependencies(
|
||||
DynamicConfiguration.class, dynamicConfigurationExecutor, awsCredentialsProvider);
|
||||
dynamicConfigurationManager.start();
|
||||
|
||||
MetricsUtil.configureRegistries(configuration, environment, dynamicConfigurationManager);
|
||||
|
||||
final ClientResources.Builder redisClientResourcesBuilder = ClientResources.builder();
|
||||
|
||||
FaultTolerantRedisCluster cacheCluster = configuration.getCacheClusterConfiguration().build("main_cache",
|
||||
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package org.whispersystems.textsecuregcm.workers;
|
||||
|
||||
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.scheduler.JobScheduler;
|
||||
|
||||
public interface JobSchedulerFactory {
|
||||
|
||||
JobScheduler buildJobScheduler(CommandDependencies commandDependencies, WhisperServerConfiguration configuration);
|
||||
}
|
||||
+1
@@ -49,6 +49,7 @@ public class MessagePersisterServiceCommand extends ServerCommand<WhisperServerC
|
||||
UncaughtExceptionHandler.register();
|
||||
|
||||
final CommandDependencies deps = CommandDependencies.build("message-persister-service", environment, configuration);
|
||||
MetricsUtil.configureRegistries(configuration, environment, deps.dynamicConfigurationManager());
|
||||
|
||||
if (configuration.getServerFactory() instanceof DefaultServerFactory defaultServerFactory) {
|
||||
defaultServerFactory.getApplicationConnectors()
|
||||
|
||||
-160
@@ -1,160 +0,0 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.workers;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Optional;
|
||||
import net.sourceforge.argparse4j.inf.Subparser;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
public class ProcessPushNotificationFeedbackCommand extends AbstractSinglePassCrawlAccountsCommand {
|
||||
|
||||
private final Clock clock;
|
||||
|
||||
@VisibleForTesting
|
||||
static final Duration MAX_TOKEN_REFRESH_DELAY = Duration.ofDays(3);
|
||||
|
||||
@VisibleForTesting
|
||||
static final String DRY_RUN_ARGUMENT = "dry-run";
|
||||
|
||||
private static final int MAX_CONCURRENCY = 16;
|
||||
|
||||
private static final String EXPIRED_DEVICE_COUNTER_NAME =
|
||||
MetricsUtil.name(ProcessPushNotificationFeedbackCommand.class, "expiredDevice");
|
||||
|
||||
private static final String RECOVERED_DEVICE_COUNTER_NAME =
|
||||
MetricsUtil.name(ProcessPushNotificationFeedbackCommand.class, "recoveredDevice");
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(ProcessPushNotificationFeedbackCommand.class);
|
||||
|
||||
public ProcessPushNotificationFeedbackCommand(final Clock clock) {
|
||||
super("process-push-notification-feedback", "");
|
||||
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void configure(final Subparser subparser) {
|
||||
super.configure(subparser);
|
||||
|
||||
subparser.addArgument("--dry-run")
|
||||
.type(Boolean.class)
|
||||
.dest(DRY_RUN_ARGUMENT)
|
||||
.required(false)
|
||||
.setDefault(true)
|
||||
.help("If true, don't actually modify accounts with stale devices");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void crawlAccounts(final Flux<Account> accounts) {
|
||||
final boolean isDryRun = getNamespace().getBoolean(DRY_RUN_ARGUMENT);
|
||||
|
||||
accounts
|
||||
.filter(account -> account.getDevices().stream().anyMatch(this::deviceNeedsUpdate))
|
||||
.flatMap(account -> {
|
||||
account.getDevices().stream()
|
||||
.filter(this::deviceNeedsUpdate)
|
||||
.forEach(device -> {
|
||||
final Tags tags = Tags.of(
|
||||
UserAgentTagUtil.PLATFORM_TAG, getPlatform(device),
|
||||
"dryRun", String.valueOf(isDryRun));
|
||||
|
||||
if (deviceExpired(device)) {
|
||||
Metrics.counter(EXPIRED_DEVICE_COUNTER_NAME, tags).increment();
|
||||
} else {
|
||||
Metrics.counter(RECOVERED_DEVICE_COUNTER_NAME, tags).increment();
|
||||
}
|
||||
});
|
||||
|
||||
if (isDryRun) {
|
||||
return Mono.just(account);
|
||||
} else {
|
||||
return Mono.fromFuture(() -> getCommandDependencies().accountsManager().updateAsync(account,
|
||||
a -> a.getDevices().stream()
|
||||
.filter(this::deviceNeedsUpdate)
|
||||
.forEach(device -> {
|
||||
if (deviceExpired(device)) {
|
||||
getUserAgent(device).ifPresent(device::setUserAgent);
|
||||
|
||||
device.setGcmId(null);
|
||||
device.setApnId(null);
|
||||
device.setVoipApnId(null);
|
||||
device.setFetchesMessages(false);
|
||||
} else {
|
||||
device.setUninstalledFeedbackTimestamp(0);
|
||||
}
|
||||
})))
|
||||
.onErrorResume(throwable -> {
|
||||
log.warn("Failed to process push notification feedback for account {}", account.getUuid(), throwable);
|
||||
return Mono.empty();
|
||||
});
|
||||
}
|
||||
}, MAX_CONCURRENCY)
|
||||
.then()
|
||||
.block();
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
boolean pushFeedbackIntervalElapsed(final Device device) {
|
||||
// After we get an indication that a device may have uninstalled the Signal app (`uninstalledFeedbackTimestamp` is
|
||||
// non-zero), check back in after a few days to see what ultimately happened.
|
||||
return device.getUninstalledFeedbackTimestamp() != 0 &&
|
||||
Instant.ofEpochMilli(device.getUninstalledFeedbackTimestamp()).plus(MAX_TOKEN_REFRESH_DELAY)
|
||||
.isBefore(clock.instant());
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
boolean deviceExpired(final Device device) {
|
||||
// If we received an indication that a device may have uninstalled the Signal app and we haven't seen that device in
|
||||
// a few days since that event, we consider the device "expired" and should clean up its push tokens. If we have
|
||||
// seen the device recently, though, we assume that the "uninstalled" hint was either incorrect or the device has
|
||||
// since reinstalled the app and provided new push tokens.
|
||||
return Instant.ofEpochMilli(device.getLastSeen()).plus(MAX_TOKEN_REFRESH_DELAY).isBefore(clock.instant());
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
boolean deviceNeedsUpdate(final Device device) {
|
||||
return pushFeedbackIntervalElapsed(device) && (device.isEnabled() || device.getLastSeen() > device.getUninstalledFeedbackTimestamp());
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static Optional<String> getUserAgent(final Device device) {
|
||||
if (StringUtils.isNotBlank(device.getApnId())) {
|
||||
if (device.isPrimary()) {
|
||||
return Optional.of("OWI");
|
||||
} else {
|
||||
return Optional.of("OWP");
|
||||
}
|
||||
} else if (StringUtils.isNotBlank(device.getGcmId())) {
|
||||
return Optional.of("OWA");
|
||||
}
|
||||
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
private static String getPlatform(final Device device) {
|
||||
if (StringUtils.isNotBlank(device.getApnId())) {
|
||||
return "ios";
|
||||
} else if (StringUtils.isNotBlank(device.getGcmId())) {
|
||||
return "android";
|
||||
}
|
||||
|
||||
return "unrecognized";
|
||||
}
|
||||
}
|
||||
+133
@@ -0,0 +1,133 @@
|
||||
package org.whispersystems.textsecuregcm.workers;
|
||||
|
||||
import io.dropwizard.core.Application;
|
||||
import io.dropwizard.core.cli.ServerCommand;
|
||||
import io.dropwizard.core.server.DefaultServerFactory;
|
||||
import io.dropwizard.core.setup.Environment;
|
||||
import io.dropwizard.jetty.HttpsConnectorFactory;
|
||||
import io.dropwizard.lifecycle.Managed;
|
||||
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.scheduler.JobScheduler;
|
||||
import org.whispersystems.textsecuregcm.util.logging.UncaughtExceptionHandler;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ScheduledFuture;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
public class ProcessScheduledJobsServiceCommand extends ServerCommand<WhisperServerConfiguration> {
|
||||
|
||||
private final String name;
|
||||
private final JobSchedulerFactory jobSchedulerFactory;
|
||||
|
||||
private static final String FIXED_DELAY_SECONDS_ARGUMENT = "fixedDelay";
|
||||
private static final int DEFAULT_FIXED_DELAY_SECONDS = 60;
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(ProcessScheduledJobsServiceCommand.class);
|
||||
|
||||
private static class ScheduledJobProcessor implements Managed {
|
||||
|
||||
private final JobScheduler jobScheduler;
|
||||
|
||||
private final ScheduledExecutorService scheduledExecutorService;
|
||||
private final int fixedDelaySeconds;
|
||||
|
||||
private ScheduledFuture<?> processJobsFuture;
|
||||
|
||||
private ScheduledJobProcessor(final JobScheduler jobScheduler,
|
||||
final ScheduledExecutorService scheduledExecutorService,
|
||||
final int fixedDelaySeconds) {
|
||||
|
||||
this.jobScheduler = jobScheduler;
|
||||
this.scheduledExecutorService = scheduledExecutorService;
|
||||
this.fixedDelaySeconds = fixedDelaySeconds;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void start() {
|
||||
processJobsFuture = scheduledExecutorService.scheduleWithFixedDelay(() -> {
|
||||
try {
|
||||
jobScheduler.processAvailableJobs().join();
|
||||
} catch (final Exception e) {
|
||||
log.warn("Failed to process available jobs for scheduler: {}", jobScheduler.getSchedulerName(), e);
|
||||
}
|
||||
}, 0, fixedDelaySeconds, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stop() {
|
||||
if (processJobsFuture != null) {
|
||||
processJobsFuture.cancel(false);
|
||||
}
|
||||
|
||||
processJobsFuture = null;
|
||||
}
|
||||
}
|
||||
|
||||
public ProcessScheduledJobsServiceCommand(final String name,
|
||||
final String description,
|
||||
final JobSchedulerFactory jobSchedulerFactory) {
|
||||
|
||||
super(new Application<>() {
|
||||
@Override
|
||||
public void run(WhisperServerConfiguration configuration, Environment environment) {
|
||||
}
|
||||
}, name,
|
||||
description);
|
||||
|
||||
this.name = name;
|
||||
this.jobSchedulerFactory = jobSchedulerFactory;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void configure(final Subparser subparser) {
|
||||
super.configure(subparser);
|
||||
|
||||
subparser.addArgument("--fixed-delay")
|
||||
.type(Integer.class)
|
||||
.dest(FIXED_DELAY_SECONDS_ARGUMENT)
|
||||
.setDefault(DEFAULT_FIXED_DELAY_SECONDS)
|
||||
.help("The delay, in seconds, between queries for jobs to process");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void run(final Environment environment,
|
||||
final Namespace namespace,
|
||||
final WhisperServerConfiguration configuration)
|
||||
throws Exception {
|
||||
|
||||
UncaughtExceptionHandler.register();
|
||||
|
||||
final CommandDependencies commandDependencies = CommandDependencies.build(name, environment, configuration);
|
||||
|
||||
final int fixedDelaySeconds = namespace.getInt(FIXED_DELAY_SECONDS_ARGUMENT);
|
||||
|
||||
MetricsUtil.configureRegistries(configuration, environment, commandDependencies.dynamicConfigurationManager());
|
||||
|
||||
// Even though we're not actually serving traffic, `ServerCommand` subclasses need a valid server configuration, and
|
||||
// that means they need to be able to decrypt the TLS keystore.
|
||||
if (configuration.getServerFactory() instanceof DefaultServerFactory defaultServerFactory) {
|
||||
defaultServerFactory.getApplicationConnectors()
|
||||
.forEach(connectorFactory -> {
|
||||
if (connectorFactory instanceof HttpsConnectorFactory h) {
|
||||
h.setKeyStorePassword(configuration.getTlsKeyStoreConfiguration().password().value());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
final ScheduledExecutorService scheduledExecutorService =
|
||||
environment.lifecycle().scheduledExecutorService("scheduled-job-processor-%d", false)
|
||||
.build();
|
||||
|
||||
final JobScheduler jobScheduler = jobSchedulerFactory.buildJobScheduler(commandDependencies, configuration);
|
||||
|
||||
environment.lifecycle().manage(new ScheduledJobProcessor(jobScheduler, scheduledExecutorService, fixedDelaySeconds));
|
||||
|
||||
MetricsUtil.registerSystemResourceMetrics(environment);
|
||||
|
||||
super.run(environment, namespace, configuration);
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -26,7 +26,7 @@ public class RemoveExpiredAccountsCommand extends AbstractSinglePassCrawlAccount
|
||||
private final Clock clock;
|
||||
|
||||
@VisibleForTesting
|
||||
static final Duration MAX_IDLE_DURATION = Duration.ofDays(180);
|
||||
static final Duration MAX_IDLE_DURATION = Duration.ofDays(120);
|
||||
|
||||
@VisibleForTesting
|
||||
static final String DRY_RUN_ARGUMENT = "dry-run";
|
||||
|
||||
+1
@@ -53,6 +53,7 @@ public class ScheduledApnPushNotificationSenderServiceCommand extends ServerComm
|
||||
UncaughtExceptionHandler.register();
|
||||
|
||||
final CommandDependencies deps = CommandDependencies.build("scheduled-apn-sender", environment, configuration);
|
||||
MetricsUtil.configureRegistries(configuration, environment, deps.dynamicConfigurationManager());
|
||||
|
||||
if (configuration.getServerFactory() instanceof DefaultServerFactory defaultServerFactory) {
|
||||
defaultServerFactory.getApplicationConnectors()
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
# Chat gRPC API
|
||||
|
||||
## Errors
|
||||
|
||||
The chat-server gRPC API uses the [well-defined gRPC status codes](https://grpc.github.io/grpc/core/md_doc_statuscodes.html) returned as part of every RPC call. Common error conditions in the API are mapped to some status code and rather than being explicitly represented in the RPC messages. Broadly, there are 3 categories of errors:
|
||||
|
||||
1. Common status errors: gRPC error status that should be handled identically across many RPC calls
|
||||
2. Domain specific status errors: gRPC error statuses that accurately represent an error case of an individual RPC
|
||||
3. Domain specific custom errors: Errors represented explicitly in the protobuf return type for an RPC call
|
||||
|
||||
Server APIs attempt to include additional debugging information about the nature of the error in the detail string of the status. Status messages may change at any time and are intended only as a debugging aid; consumers of status messages must never make assumptions about their structure or content.
|
||||
### Common status errors
|
||||
|
||||
Common status errors are errors that may be handled similarly, regardless of which RPC is being called. This usually means retrying, ignoring, or logging for bug reporting. For example, the chat gRPC API reserves `RESOURCE_EXHAUSTED` for temporary exhaustion of a per-user resource. Regardless of the RPC being called, the caller should handle this error by retrying with a backoff, using the `retry-after` time interval specified via trailing metadata if the server provides it.
|
||||
|
||||
Common status errors are unexpected. They represent a transient condition that causes requests to fail or a misbehaving client/server. Errors expected in the normal path of operation should use one of the domain specific error types. For example, looking up a username that does not exist by hash does _not_ return common status error since that is an expected response. However, if the lookup request does not contain a valid hash, that _is_ a common status error because it means the client did not properly construct the request.
|
||||
|
||||
Currently, any RPC may return one of these common errors. Unless otherwise indicated, consult the [gRPC docs](https://grpc.github.io/grpc/core/md_doc_statuscodes.html) for their interpretation.
|
||||
|
||||
|
||||
| code | number | notes |
|
||||
|----------------------|--------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| `UNKNOWN` | 2 | |
|
||||
| `INVALID_ARGUMENT` | 3 | Violates some constraint documented in the message protobuf. Constraints may be expressed via comments or custom `require` annotations on the request. |
|
||||
| `RESOURCE_EXHAUSTED` | 8 | A per-user resource has been temporarily exhausted (usually a rate-limit). A `retry-after` header containing an ISO8601 duration string may be present in the response headers, indicating how long it will be before a retry can succeed. |
|
||||
| `INTERNAL` | 13 | |
|
||||
| `UNAVAILABLE` | 14 | |
|
||||
| `UNAUTHENTICATED` | 16 | Indicates some problem with the caller's authentication status. For example, calling an authenticated endpoint from an unauthenticated connection, or calling an group send endorsement (GSE) authenticated endpoint with an invalid GSE. |
|
||||
|
||||
|
||||
If one of these errors has a more specific meaning for a certain RPC, it will be documented on the RPC. Note this section does not include errors that may be generated on the client side (like `CANCELLED` or `DEADLINE_EXCEEDED`), consult your client's gRPC documentation.
|
||||
|
||||
### Domain specific status errors
|
||||
|
||||
Occasionally, an RPC will return a status error for a widely understood error scenario that is not applicable across all RPCs or has some domain specific handling. For example, sending a message to a user may return `NOT_FOUND` if that user does not exist.
|
||||
|
||||
Any domain specific errors will always be documented on the RPC or enclosing service.
|
||||
|
||||
### Domain specific custom errors
|
||||
|
||||
All other errors are explicitly represented as part of the response definitions for the RPC. Typically, an RPC will provide custom errors when:
|
||||
- No gRPC status maps to the represented error
|
||||
- Additional structured data needs to be returned along with the error(s)
|
||||
- The error does not represent a client bug, but requires handling beyond retrying or ignoring
|
||||
@@ -148,6 +148,7 @@ message SetCapabilitiesRequest {
|
||||
bool storage = 1;
|
||||
bool transfer = 2;
|
||||
bool paymentActivation = 3;
|
||||
bool deleteSync = 4;
|
||||
}
|
||||
|
||||
message SetCapabilitiesResponse {}
|
||||
@@ -323,9 +323,9 @@ message UserCapabilities {
|
||||
*/
|
||||
bool payment_activation = 1;
|
||||
/**
|
||||
* Whether all devices linked to the account support phone number privacy.
|
||||
* Whether all devices linked to the account support delete syncing
|
||||
*/
|
||||
bool pni = 2;
|
||||
bool delete_sync = 2;
|
||||
}
|
||||
|
||||
message Badge {
|
||||
|
||||
@@ -13,123 +13,134 @@ import "google/protobuf/descriptor.proto";
|
||||
|
||||
extend google.protobuf.FieldOptions {
|
||||
/*
|
||||
Requires a field to have content of non-zero size/length.
|
||||
Applies to both `optional` and regular fields, i.e. if the field is not set or has a default value,
|
||||
it's considered to be empty.
|
||||
|
||||
```
|
||||
import "org/signal/chat/require.proto";
|
||||
|
||||
message Data {
|
||||
|
||||
string nonEmptyString = 1 [(require.nonEmpty) = true];
|
||||
|
||||
bytes nonEmptyBytes = 2 [(require.nonEmpty) = true];
|
||||
|
||||
optional string nonEmptyStringOptional = 3 [(require.nonEmpty) = true];
|
||||
|
||||
optional bytes nonEmptyBytesOptional = 4 [(require.nonEmpty) = true];
|
||||
|
||||
repeated string nonEmptyList = 5 [(require.nonEmpty) = true];
|
||||
}
|
||||
```
|
||||
|
||||
Applicable to fields of type `string`, `byte`, and `repeated` fields.
|
||||
* Requires a field to have content of non-zero size/length.
|
||||
* Applies to both `optional` and regular fields, i.e. if the field is not set or has a default value,
|
||||
* it's considered to be empty.
|
||||
*
|
||||
* ```
|
||||
* import "org/signal/chat/require.proto";
|
||||
*
|
||||
* message Data {
|
||||
* string nonEmptyString = 1 [(require.nonEmpty) = true];
|
||||
* bytes nonEmptyBytes = 2 [(require.nonEmpty) = true];
|
||||
* optional string nonEmptyStringOptional = 3 [(require.nonEmpty) = true];
|
||||
* optional bytes nonEmptyBytesOptional = 4 [(require.nonEmpty) = true];
|
||||
* repeated string nonEmptyList = 5 [(require.nonEmpty) = true];
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* Applicable to fields of type `string`, `byte`, and `repeated` fields.
|
||||
*/
|
||||
optional bool nonEmpty = 70001;
|
||||
|
||||
/*
|
||||
Requires a enum field to have value with an index greater than zero.
|
||||
Applies to both `optional` and regular fields, i.e. if the field is not set or has a default value,
|
||||
its index will be <= 0.
|
||||
|
||||
```
|
||||
import "org/signal/chat/require.proto";
|
||||
|
||||
message Data {
|
||||
Color color = 1 [(require.specified) = true];
|
||||
}
|
||||
|
||||
enum Color {
|
||||
COLOR_UNSPECIFIED = 0;
|
||||
COLOR_RED = 1;
|
||||
COLOR_GREEN = 2;
|
||||
COLOR_BLUE = 3;
|
||||
}
|
||||
```
|
||||
* Requires a enum field to have value with an index greater than zero.
|
||||
* Applies to both `optional` and regular fields, i.e. if the field is not set or has a default value,
|
||||
* its index will be <= 0.
|
||||
*
|
||||
* ```
|
||||
* import "org/signal/chat/require.proto";
|
||||
*
|
||||
* message Data {
|
||||
* Color color = 1 [(require.specified) = true];
|
||||
* }
|
||||
*
|
||||
* enum Color {
|
||||
* COLOR_UNSPECIFIED = 0;
|
||||
* COLOR_RED = 1;
|
||||
* COLOR_GREEN = 2;
|
||||
* COLOR_BLUE = 3;
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
optional bool specified = 70002;
|
||||
|
||||
/*
|
||||
Requires a size/length of a field to be within certain boundaries.
|
||||
Applies to both `optional` and regular fields, i.e. if the field is not set or has a default value,
|
||||
its size considered to be zero.
|
||||
|
||||
```
|
||||
import "org/signal/chat/require.proto";
|
||||
|
||||
message Data {
|
||||
|
||||
string name = 1 [(require.size) = {min: 3, max: 8}];
|
||||
|
||||
optional string address = 2 [(require.size) = {min: 3, max: 8}];
|
||||
}
|
||||
```
|
||||
|
||||
Applicable to fields of type `string`, `byte`, and `repeated` fields.
|
||||
* Requires a size/length of a field to be within certain boundaries.
|
||||
* Applies to both `optional` and regular fields, i.e. if the field is not set or has a default value,
|
||||
* its size considered to be zero.
|
||||
*
|
||||
* ```
|
||||
* import "org/signal/chat/require.proto";
|
||||
*
|
||||
* message Data {
|
||||
*
|
||||
* string name = 1 [(require.size) = {min: 3, max: 8}];
|
||||
*
|
||||
* optional string address = 2 [(require.size) = {min: 3, max: 8}];
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* Applicable to fields of type `string`, `byte`, and `repeated` fields.
|
||||
*/
|
||||
optional SizeConstraint size = 70003;
|
||||
|
||||
/*
|
||||
Requires a size/length of a field to be one of the specified values.
|
||||
Applies to both `optional` and regular fields, i.e. if the field is not set or has a default value,
|
||||
its size considered to be zero.
|
||||
|
||||
```
|
||||
import "org/signal/chat/require.proto";
|
||||
|
||||
message Data {
|
||||
|
||||
string zip = 1 [(require.exactlySize) = 5];
|
||||
|
||||
optional string exactlySizeVariants = 2 [(require.exactlySize) = 2, (require.exactlySize) = 4];
|
||||
}
|
||||
```
|
||||
|
||||
Applicable to fields of type `string`, `byte`, and `repeated` fields.
|
||||
* Requires a size/length of a field to be one of the specified values.
|
||||
* Applies to both `optional` and regular fields, i.e. if the field is not set or has a default value,
|
||||
* its size considered to be zero.
|
||||
*
|
||||
* ```
|
||||
* import "org/signal/chat/require.proto";
|
||||
*
|
||||
* message Data {
|
||||
*
|
||||
* string zip = 1 [(require.exactlySize) = 5];
|
||||
*
|
||||
* optional string exactlySizeVariants = 2 [(require.exactlySize) = 2, (require.exactlySize) = 4];
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* Applicable to fields of type `string`, `byte`, and `repeated` fields.
|
||||
*/
|
||||
repeated uint32 exactlySize = 70004;
|
||||
|
||||
/*
|
||||
Requires a value of a string field to be a valid E164-normalized phone number.
|
||||
If the field is `optional`, this check allows a value to be not set.
|
||||
|
||||
```
|
||||
import "org/signal/chat/require.proto";
|
||||
|
||||
message Data {
|
||||
string number = 1 [(require.e164)];
|
||||
}
|
||||
```
|
||||
* Requires a value of a string field to be a valid E164-normalized phone number.
|
||||
* If the field is `optional`, this check allows a value to be not set.
|
||||
*
|
||||
* ```
|
||||
* import "org/signal/chat/require.proto";
|
||||
*
|
||||
* message Data {
|
||||
* string number = 1 [(require.e164)];
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
optional bool e164 = 70005;
|
||||
|
||||
/*
|
||||
Requires an integer value to be within a certain range. The range boundaries are specified
|
||||
with the values of type `int32`, which should be enough for all practical purposes.
|
||||
|
||||
If the field is `optional`, this check allows a value to be not set.
|
||||
|
||||
```
|
||||
import "org/signal/chat/require.proto";
|
||||
|
||||
message Data {
|
||||
int32 byte = 1 [(require.range) = {min = -128, max = 127}];
|
||||
uint32 unsignedByte = 2 [(require.range).max = 255];
|
||||
}
|
||||
```
|
||||
* Requires an integer value to be within a certain range. The range boundaries are specified
|
||||
* with the values of type `int32`, which should be enough for all practical purposes.
|
||||
*
|
||||
* If the field is `optional`, this check allows a value to be not set.
|
||||
*
|
||||
* ```
|
||||
* import "org/signal/chat/require.proto";
|
||||
*
|
||||
* message Data {
|
||||
* int32 byte = 1 [(require.range) = {min: -128, max: 127}];
|
||||
* uint32 unsignedByte = 2 [(require.range).max = 255];
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
optional ValueRangeConstraint range = 70006;
|
||||
|
||||
/*
|
||||
* Require a value of a message field to be present.
|
||||
*
|
||||
* Applies to both `optional` and regular fields (both of which have explicit
|
||||
* presence for the message type anyways)
|
||||
*
|
||||
* ```
|
||||
* import "org/signal/chat/require.proto";
|
||||
* message Data {
|
||||
* message MyMessage {}
|
||||
* MyMessage myMessage = 1 [(require.present) = true];
|
||||
* }
|
||||
*````
|
||||
*/
|
||||
optional bool present = 70007;
|
||||
}
|
||||
|
||||
message SizeConstraint {
|
||||
@@ -144,17 +155,17 @@ message ValueRangeConstraint {
|
||||
|
||||
extend google.protobuf.ServiceOptions {
|
||||
/*
|
||||
Indicates that all methods in a given service require a certain kind of authentication.
|
||||
|
||||
```
|
||||
import "org/signal/chat/require.proto";
|
||||
|
||||
service AuthService {
|
||||
option (require.auth) = AUTH_ONLY_AUTHENTICATED;
|
||||
|
||||
rpc AuthenticatedMethod (google.protobuf.Empty) returns (google.protobuf.Empty) {}
|
||||
}
|
||||
```
|
||||
* Indicates that all methods in a given service require a certain kind of authentication.
|
||||
*
|
||||
* ```
|
||||
* import "org/signal/chat/require.proto";
|
||||
*
|
||||
* service AuthService {
|
||||
* option (require.auth) = AUTH_ONLY_AUTHENTICATED;
|
||||
*
|
||||
* rpc AuthenticatedMethod (google.protobuf.Empty) returns (google.protobuf.Empty) {}
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
optional Auth auth = 71001;
|
||||
}
|
||||
|
||||
+1
@@ -1 +1,2 @@
|
||||
org.whispersystems.textsecuregcm.util.logging.RequestLogEnabledFilterFactory
|
||||
org.whispersystems.textsecuregcm.util.logging.UnknownKeepaliveOptionFilterFactory
|
||||
+10
-1
@@ -6,6 +6,7 @@
|
||||
package org.whispersystems.textsecuregcm;
|
||||
|
||||
import io.dropwizard.util.Resources;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* This class may be run directly from a correctly configured IDE, or using the command line:
|
||||
@@ -13,9 +14,14 @@ import io.dropwizard.util.Resources;
|
||||
* <code>./mvnw clean integration-test -DskipTests=true -Ptest-server</code>
|
||||
* <p>
|
||||
* <strong>NOTE: many features are non-functional, especially those that depend on external services</strong>
|
||||
* <p>
|
||||
* By default, it will use {@code config/test.yml}, but this may be overridden by setting an environment variable,
|
||||
* {@value SIGNAL_SERVER_CONFIG_ENV_VAR}, with a custom path.
|
||||
*/
|
||||
public class LocalWhisperServerService {
|
||||
|
||||
private static final String SIGNAL_SERVER_CONFIG_ENV_VAR = "SIGNAL_SERVER_CONFIG";
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
|
||||
System.setProperty("secrets.bundle.filename",
|
||||
@@ -23,6 +29,9 @@ public class LocalWhisperServerService {
|
||||
System.setProperty("sqlite.dir", "service/target/lib");
|
||||
System.setProperty("aws.region", "local-test-region");
|
||||
|
||||
new WhisperServerService().run("server", Resources.getResource("config/test.yml").getPath());
|
||||
final String config = Optional.ofNullable(System.getenv(SIGNAL_SERVER_CONFIG_ENV_VAR))
|
||||
.orElse(Resources.getResource("config/test.yml").getPath());
|
||||
|
||||
new WhisperServerService().run("server", config);
|
||||
}
|
||||
}
|
||||
-12
@@ -161,9 +161,7 @@ class AccountAuthenticatorTest {
|
||||
when(accountsManager.getByAccountIdentifier(uuid)).thenReturn(Optional.of(account));
|
||||
when(account.getUuid()).thenReturn(uuid);
|
||||
when(account.getDevice(deviceId)).thenReturn(Optional.of(device));
|
||||
when(account.isEnabled()).thenReturn(true);
|
||||
when(device.getId()).thenReturn(deviceId);
|
||||
when(device.isEnabled()).thenReturn(true);
|
||||
when(device.getAuthTokenHash()).thenReturn(credentials);
|
||||
when(credentials.verify(password)).thenReturn(true);
|
||||
when(credentials.getVersion()).thenReturn(SaltedTokenHash.CURRENT_VERSION);
|
||||
@@ -191,9 +189,7 @@ class AccountAuthenticatorTest {
|
||||
when(accountsManager.getByAccountIdentifier(uuid)).thenReturn(Optional.of(account));
|
||||
when(account.getUuid()).thenReturn(uuid);
|
||||
when(account.getDevice(deviceId)).thenReturn(Optional.of(device));
|
||||
when(account.isEnabled()).thenReturn(true);
|
||||
when(device.getId()).thenReturn(deviceId);
|
||||
when(device.isEnabled()).thenReturn(true);
|
||||
when(device.getAuthTokenHash()).thenReturn(credentials);
|
||||
when(credentials.verify(password)).thenReturn(true);
|
||||
when(credentials.getVersion()).thenReturn(SaltedTokenHash.CURRENT_VERSION);
|
||||
@@ -224,9 +220,7 @@ class AccountAuthenticatorTest {
|
||||
when(accountsManager.getByAccountIdentifier(uuid)).thenReturn(Optional.of(account));
|
||||
when(account.getUuid()).thenReturn(uuid);
|
||||
when(account.getDevice(deviceId)).thenReturn(Optional.of(authenticatedDevice));
|
||||
when(account.isEnabled()).thenReturn(accountEnabled);
|
||||
when(authenticatedDevice.getId()).thenReturn(deviceId);
|
||||
when(authenticatedDevice.isEnabled()).thenReturn(deviceEnabled);
|
||||
when(authenticatedDevice.getAuthTokenHash()).thenReturn(credentials);
|
||||
when(credentials.verify(password)).thenReturn(true);
|
||||
when(credentials.getVersion()).thenReturn(SaltedTokenHash.CURRENT_VERSION);
|
||||
@@ -260,9 +254,7 @@ class AccountAuthenticatorTest {
|
||||
when(accountsManager.getByAccountIdentifier(uuid)).thenReturn(Optional.of(account));
|
||||
when(account.getUuid()).thenReturn(uuid);
|
||||
when(account.getDevice(deviceId)).thenReturn(Optional.of(device));
|
||||
when(account.isEnabled()).thenReturn(true);
|
||||
when(device.getId()).thenReturn(deviceId);
|
||||
when(device.isEnabled()).thenReturn(true);
|
||||
when(device.getAuthTokenHash()).thenReturn(credentials);
|
||||
when(credentials.verify(password)).thenReturn(true);
|
||||
when(credentials.getVersion()).thenReturn(SaltedTokenHash.Version.V1);
|
||||
@@ -297,9 +289,7 @@ class AccountAuthenticatorTest {
|
||||
when(accountsManager.getByAccountIdentifier(uuid)).thenReturn(Optional.of(account));
|
||||
when(account.getUuid()).thenReturn(uuid);
|
||||
when(account.getDevice(deviceId)).thenReturn(Optional.of(device));
|
||||
when(account.isEnabled()).thenReturn(true);
|
||||
when(device.getId()).thenReturn(deviceId);
|
||||
when(device.isEnabled()).thenReturn(true);
|
||||
when(device.getAuthTokenHash()).thenReturn(credentials);
|
||||
when(credentials.verify(password)).thenReturn(true);
|
||||
when(credentials.getVersion()).thenReturn(SaltedTokenHash.CURRENT_VERSION);
|
||||
@@ -325,9 +315,7 @@ class AccountAuthenticatorTest {
|
||||
when(accountsManager.getByAccountIdentifier(uuid)).thenReturn(Optional.of(account));
|
||||
when(account.getUuid()).thenReturn(uuid);
|
||||
when(account.getDevice(deviceId)).thenReturn(Optional.of(device));
|
||||
when(account.isEnabled()).thenReturn(true);
|
||||
when(device.getId()).thenReturn(deviceId);
|
||||
when(device.isEnabled()).thenReturn(true);
|
||||
when(device.getAuthTokenHash()).thenReturn(credentials);
|
||||
when(credentials.verify(password)).thenReturn(true);
|
||||
when(credentials.getVersion()).thenReturn(SaltedTokenHash.CURRENT_VERSION);
|
||||
|
||||
Loaded 100 of 179 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user