mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-12-01 06:06:47 +00:00
Compare commits
31
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4ab58e950b | ||
|
|
7f301cbf95 | ||
|
|
5a7660d3ae | ||
|
|
850172f6a3 | ||
|
|
4e73162055 | ||
|
|
4127cf90ab | ||
|
|
08cc7bc462 | ||
|
|
2cf2391f38 | ||
|
|
007dde8d45 | ||
|
|
f80e30f9f2 | ||
|
|
ff5201a58e | ||
|
|
8954708d77 | ||
|
|
3cf194e476 | ||
|
|
bad2602491 | ||
|
|
a647c1bfdf | ||
|
|
1bba30a81e | ||
|
|
827d8388d0 | ||
|
|
70efb19a86 | ||
|
|
35ffb208e3 | ||
|
|
e50dcd185d | ||
|
|
1cd446ee31 | ||
|
|
1847c6d4ca | ||
|
|
1770558d5e | ||
|
|
e0d39212ec | ||
|
|
31ebe9071a | ||
|
|
8f65486fab | ||
|
|
7e3540bda0 | ||
|
|
c544628dfe | ||
|
|
61b162d0a1 | ||
|
|
8c2d738924 | ||
|
|
efde8a31f9 |
No files matched your search
@@ -11,8 +11,8 @@ jobs:
|
||||
contents: write
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||
- uses: actions/setup-java@3a4f6e1af504cf6a31855fa899c6aa5355ba6c12 # v4.7.0
|
||||
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
|
||||
- uses: actions/setup-java@dded0888837ed1f317902acf8a20df0ad188d165 # v5.0.0
|
||||
with:
|
||||
distribution: 'temurin'
|
||||
java-version-file: .java-version
|
||||
|
||||
@@ -18,13 +18,13 @@ jobs:
|
||||
id-token: write
|
||||
contents: read
|
||||
steps:
|
||||
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||
- uses: actions/setup-java@c5195efecf7bdfc987ee8bae7a71cb8b11521c00 # v4.7.1
|
||||
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
|
||||
- uses: actions/setup-java@dded0888837ed1f317902acf8a20df0ad188d165 # v5.0.0
|
||||
with:
|
||||
distribution: 'temurin'
|
||||
java-version-file: .java-version
|
||||
cache: 'maven'
|
||||
- uses: aws-actions/configure-aws-credentials@b47578312673ae6fa5b5096b330d9fbac3d116df # v4.2.1
|
||||
- uses: aws-actions/configure-aws-credentials@b47578312673ae6fa5b5096b330d9fbac3d116df # v5.0.0
|
||||
name: Configure AWS credentials from Test account
|
||||
with:
|
||||
role-to-assume: ${{ vars.AWS_ROLE }}
|
||||
|
||||
@@ -25,9 +25,9 @@ jobs:
|
||||
options: --name foundationdb1
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
|
||||
- name: Set up JDK
|
||||
uses: actions/setup-java@3a4f6e1af504cf6a31855fa899c6aa5355ba6c12 # v4.7.0
|
||||
uses: actions/setup-java@dded0888837ed1f317902acf8a20df0ad188d165 # v5.0.0
|
||||
with:
|
||||
distribution: 'temurin'
|
||||
java-version-file: .java-version
|
||||
|
||||
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.9/apache-maven-3.9.9-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=4ec3f26fb1a692473aea0235c300bd20f0f9fe741947c82c1234cefd76ac3a3c
|
||||
wrapperSha256Sum=3d8f20ce6103913be8b52aef6d994e0c54705fb527324ceb9b835b338739c7a8
|
||||
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.11/apache-maven-3.9.11-bin.zip
|
||||
wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.3.4/maven-wrapper-3.3.4.jar
|
||||
distributionSha256Sum=0d7125e8c91097b36edb990ea5934e6c68b4440eef4ea96510a0f6815e7eeadb
|
||||
wrapperSha256Sum=4e2fbf6554bc8a4702cdfdd3bef464f423393d784ddbb037216320ce55d5e4e1
|
||||
@@ -37,11 +37,11 @@
|
||||
</modules>
|
||||
|
||||
<properties>
|
||||
<aws.sdk2.version>2.31.70</aws.sdk2.version>
|
||||
<braintree.version>3.42.0</braintree.version>
|
||||
<commons-csv.version>1.14.0</commons-csv.version>
|
||||
<commons-io.version>2.19.0</commons-io.version>
|
||||
<dropwizard.version>4.0.12</dropwizard.version>
|
||||
<aws.sdk2.version>2.33.8</aws.sdk2.version>
|
||||
<braintree.version>3.44.0</braintree.version>
|
||||
<commons-csv.version>1.14.1</commons-csv.version>
|
||||
<commons-io.version>2.20.0</commons-io.version>
|
||||
<dropwizard.version>4.0.16</dropwizard.version>
|
||||
<dropwizard-metrics-datadog.version>1.1.14</dropwizard-metrics-datadog.version>
|
||||
<!-- Note: when updating FoundationDB, also include a copy of `libfdb_c.so` from the FoundationDB release at
|
||||
src/main/jib/usr/lib/libfdb_c.so. We use x86_64 builds without AVX instructions enabled (i.e. FoundationDB versions
|
||||
@@ -50,39 +50,39 @@
|
||||
<foundationdb.version>7.3.62</foundationdb.version>
|
||||
<foundationdb.api-version>730</foundationdb.api-version>
|
||||
<foundationdb.client-library-sha256>bfed237b787fae3cde1222676e6bfbb0d218fc27bf9e903397a7a7aa96fb2d33</foundationdb.client-library-sha256>
|
||||
<google-cloud-libraries.version>26.62.0</google-cloud-libraries.version>
|
||||
<google-cloud-libraries.version>26.67.0</google-cloud-libraries.version>
|
||||
<grpc.version>1.73.0</grpc.version> <!-- should be kept in sync with the value from Google libraries-bom -->
|
||||
<gson.version>2.13.1</gson.version>
|
||||
<gson.version>2.13.2</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.19.1</jackson.version>
|
||||
<jackson.version>2.20.0</jackson.version>
|
||||
<junit-pioneer.version>2.3.0</junit-pioneer.version>
|
||||
<jsr305.version>3.0.2</jsr305.version>
|
||||
<kotlin.version>2.2.0</kotlin.version>
|
||||
<kotlin.version>2.2.20</kotlin.version>
|
||||
<!-- Logback 1.5.14+ has a null pointer bug: https://github.com/qos-ch/logback/issues/929. -->
|
||||
<logback.version>1.5.13</logback.version>
|
||||
<logback-access-common.version>2.0.5</logback-access-common.version>
|
||||
<lettuce.version>6.7.1.RELEASE</lettuce.version>
|
||||
<libphonenumber.version>9.0.8</libphonenumber.version>
|
||||
<logback-access-common.version>2.0.6</logback-access-common.version>
|
||||
<lettuce.version>6.8.1.RELEASE</lettuce.version>
|
||||
<libphonenumber.version>9.0.13</libphonenumber.version>
|
||||
<logstash.logback.version>8.1</logstash.logback.version>
|
||||
<log4j-bom.version>2.25.0</log4j-bom.version>
|
||||
<log4j-bom.version>2.25.1</log4j-bom.version>
|
||||
<luajava.version>3.5.0</luajava.version>
|
||||
<micrometer.version>1.15.1</micrometer.version>
|
||||
<netty.version>4.1.122.Final</netty.version>
|
||||
<micrometer.version>1.15.4</micrometer.version>
|
||||
<netty.version>4.1.127.Final</netty.version>
|
||||
<!-- Must be less than or equal to the value from Google libraries-bom which controls the protobuf runtime version.
|
||||
See https://protobuf.dev/support/cross-version-runtime-guarantee/. -->
|
||||
<protoc.version>4.29.4</protoc.version>
|
||||
<pushy.version>0.15.4</pushy.version>
|
||||
<reactive.grpc.version>1.2.4</reactive.grpc.version>
|
||||
<reactor-bom.version>2024.0.7</reactor-bom.version> <!-- 3.7.4, see https://github.com/reactor/reactor#bom-versioning-scheme -->
|
||||
<reactor-bom.version>2024.0.10</reactor-bom.version> <!-- 3.7.11, see https://github.com/reactor/reactor#bom-versioning-scheme -->
|
||||
<resilience4j.version>2.3.0</resilience4j.version>
|
||||
<semver4j.version>3.1.0</semver4j.version>
|
||||
<simple-grpc.version>0.1.0</simple-grpc.version>
|
||||
<slf4j.version>2.0.17</slf4j.version>
|
||||
<stripe.version>23.10.0</stripe.version>
|
||||
<swagger.version>2.2.31</swagger.version>
|
||||
<testcontainers.version>1.21.2</testcontainers.version>
|
||||
<stripe.version>28.4.0</stripe.version>
|
||||
<swagger.version>2.2.36</swagger.version>
|
||||
<testcontainers.version>1.21.3</testcontainers.version>
|
||||
|
||||
<!-- images to use in tests via testcontainers -->
|
||||
<dynamodb.image>amazon/dynamodb-local:3.0.0@sha256:2fed5e3a965a4ba5aa6ac82baec57058b5a3848e959d705518f3fd579a77e76b</dynamodb.image>
|
||||
@@ -90,8 +90,8 @@
|
||||
<redis.image>redis:7.4-alpine@sha256:af1d0fc3f63b02b13ff7906c9baf7c5b390b8881ca08119cd570677fe2f60b55</redis.image>
|
||||
<redis-cluster.image>docker.io/bitnami/redis-cluster:7.4@sha256:a53d023fdfaf8a8d7ddc58da040d3494e4cb45772644618ffa44c42dcd32b9af</redis-cluster.image>
|
||||
|
||||
<!-- eclipse-temurin:24.0.1_9-jre-noble (note: always use the multi-arch manifest *LIST* here) -->
|
||||
<docker.image.sha256>a42f2330212db8bc1459a2550def18f6ec04a8c31494ffc20dea13dfa82a211e</docker.image.sha256>
|
||||
<!-- eclipse-temurin:24.0.2_12-jre-noble (note: always use the multi-arch manifest *LIST* here) -->
|
||||
<docker.image.sha256>85ecfc9bbb42af046d2bacbf1219d2005be4840cbfa16c2e6fd910d9ccfec95b</docker.image.sha256>
|
||||
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
</properties>
|
||||
@@ -163,6 +163,20 @@
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.opentelemetry</groupId>
|
||||
<artifactId>opentelemetry-bom</artifactId>
|
||||
<version>1.54.0</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.opentelemetry.instrumentation</groupId>
|
||||
<artifactId>opentelemetry-instrumentation-bom</artifactId>
|
||||
<version>2.20.0</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.projectreactor</groupId>
|
||||
<artifactId>reactor-bom</artifactId>
|
||||
@@ -246,7 +260,7 @@
|
||||
<dependency>
|
||||
<groupId>org.ow2.asm</groupId>
|
||||
<artifactId>asm</artifactId>
|
||||
<version>9.7.1 </version>
|
||||
<version>9.8</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
@@ -272,13 +286,13 @@
|
||||
<dependency>
|
||||
<groupId>com.redis</groupId>
|
||||
<artifactId>testcontainers-redis</artifactId>
|
||||
<version>2.2.2</version>
|
||||
<version>2.2.4</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.signal</groupId>
|
||||
<artifactId>libsignal-server</artifactId>
|
||||
<version>0.76.5</version>
|
||||
<version>0.80.3</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.signal</groupId>
|
||||
@@ -352,7 +366,7 @@
|
||||
<dependency>
|
||||
<groupId>org.wiremock</groupId>
|
||||
<artifactId>wiremock</artifactId>
|
||||
<version>3.12.1</version>
|
||||
<version>3.13.1</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
@@ -551,7 +565,7 @@
|
||||
<rules>
|
||||
<dependencyConvergence/>
|
||||
<requireMavenVersion>
|
||||
<version>3.9.9</version>
|
||||
<version>3.9.11</version>
|
||||
</requireMavenVersion>
|
||||
</rules>
|
||||
</configuration>
|
||||
|
||||
+61
-18
@@ -11,11 +11,11 @@
|
||||
<artifactId>service</artifactId>
|
||||
|
||||
<properties>
|
||||
<firebase-admin.version>9.4.3</firebase-admin.version>
|
||||
<firebase-admin.version>9.6.0</firebase-admin.version>
|
||||
<java-uuid-generator.version>5.1.0</java-uuid-generator.version>
|
||||
<google-androidpublisher.version>v3-rev20250318-2.0.0</google-androidpublisher.version>
|
||||
<storekit.version>3.4.0</storekit.version>
|
||||
<webauthn4j.version>0.28.6.RELEASE</webauthn4j.version>
|
||||
<google-androidpublisher.version>v3-rev20250904-2.0.0</google-androidpublisher.version>
|
||||
<storekit.version>3.6.0</storekit.version>
|
||||
<webauthn4j.version>0.29.6.RELEASE</webauthn4j.version>
|
||||
<java-jwt.version>4.5.0</java-jwt.version>
|
||||
</properties>
|
||||
|
||||
@@ -35,7 +35,7 @@
|
||||
<artifactId>app-store-server-library</artifactId>
|
||||
<version>${storekit.version}</version>
|
||||
<exclusions>
|
||||
<!-- conflicts with okio-jvm from apollo-api-jvm -->
|
||||
<!-- conflicts with other users; resolved manually with explicit import -->
|
||||
<exclusion>
|
||||
<groupId>com.squareup.okio</groupId>
|
||||
<artifactId>okio-jvm</artifactId>
|
||||
@@ -198,6 +198,28 @@
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>io.opentelemetry</groupId>
|
||||
<artifactId>opentelemetry-sdk</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.opentelemetry</groupId>
|
||||
<artifactId>opentelemetry-exporter-otlp</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.opentelemetry.instrumentation</groupId>
|
||||
<artifactId>opentelemetry-logback-appender-1.0</artifactId>
|
||||
<!-- *all* opentelemetry-logback-appender versions are "alpha" despite the advanced version number -->
|
||||
<version>2.19.0-alpha</version>
|
||||
<exclusions>
|
||||
<!-- incubator packages aren't included in the opentelemetry BOM, and we don't use them -->
|
||||
<exclusion>
|
||||
<groupId>io.opentelemetry.instrumentation</groupId>
|
||||
<artifactId>opentelemetry-instrumentation-api-incubator</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>party.iroiro.luajava</groupId>
|
||||
<artifactId>luajava</artifactId>
|
||||
@@ -243,38 +265,47 @@
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-compress</artifactId>
|
||||
<version>1.27.1</version>
|
||||
<version>1.28.0</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.google.cloud</groupId>
|
||||
<artifactId>google-cloud-pubsub</artifactId>
|
||||
<exclusions>
|
||||
<!-- our direct import of guava brings in a more recent version of failureaccess, so excluding it here -->
|
||||
<exclusion>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>failureaccess</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
|
||||
<!-- resolve opentelemetry-semconv conflicts from lower in firebase-admin and firestore dependency trees -->
|
||||
<dependency>
|
||||
<groupId>com.google.firebase</groupId>
|
||||
<artifactId>firebase-admin</artifactId>
|
||||
<version>${firebase-admin.version}</version>
|
||||
<exclusions>
|
||||
<!-- our direct import of guava brings in a more recent version of failureaccess, so excluding it here -->
|
||||
<exclusion>
|
||||
<groupId>io.opentelemetry.semconv</groupId>
|
||||
<artifactId>opentelemetry-semconv</artifactId>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>failureaccess</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.opentelemetry.semconv</groupId>
|
||||
<artifactId>opentelemetry-semconv</artifactId>
|
||||
<version>1.30.0</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.google.cloud</groupId>
|
||||
<artifactId>google-cloud-firestore</artifactId>
|
||||
<exclusions>
|
||||
<!-- incubator packages aren't included in the opentelemetry BOM, and we don't use them -->
|
||||
<exclusion>
|
||||
<groupId>io.opentelemetry.semconv</groupId>
|
||||
<artifactId>opentelemetry-semconv</artifactId>
|
||||
<groupId>io.opentelemetry.instrumentation</groupId>
|
||||
<artifactId>opentelemetry-instrumentation-api-incubator</artifactId>
|
||||
</exclusion>
|
||||
<!-- our direct import of guava brings in a more recent version of failureaccess, so excluding it here -->
|
||||
<exclusion>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>failureaccess</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
@@ -390,7 +421,7 @@
|
||||
<dependency>
|
||||
<groupId>com.amazonaws</groupId>
|
||||
<artifactId>dynamodb-lock-client</artifactId>
|
||||
<version>1.3.0</version>
|
||||
<version>1.4.0</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
@@ -432,7 +463,7 @@
|
||||
<dependency>
|
||||
<groupId>com.googlecode.libphonenumber</groupId>
|
||||
<artifactId>geocoder</artifactId>
|
||||
<version>3.2</version>
|
||||
<version>3.14</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
@@ -544,9 +575,21 @@
|
||||
<groupId>org.jetbrains</groupId>
|
||||
<artifactId>annotations</artifactId>
|
||||
</exclusion>
|
||||
<!-- conflicts with other users; resolved manually with explicit import -->
|
||||
<exclusion>
|
||||
<groupId>com.squareup.okio</groupId>
|
||||
<artifactId>okio-jvm</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
|
||||
<!-- to resolve conflicting imports from other dependencies -->
|
||||
<dependency>
|
||||
<groupId>com.squareup.okio</groupId>
|
||||
<artifactId>okio-jvm</artifactId>
|
||||
<version>3.15.0</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<profiles>
|
||||
|
||||
@@ -63,6 +63,8 @@ import java.util.concurrent.ThreadPoolExecutor;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Stream;
|
||||
import javax.annotation.Nullable;
|
||||
import org.eclipse.jetty.websocket.core.WebSocketComponents;
|
||||
import org.eclipse.jetty.websocket.core.server.WebSocketServerComponents;
|
||||
import org.eclipse.jetty.websocket.server.config.JettyWebSocketServletContainerInitializer;
|
||||
import org.glassfish.jersey.server.ServerProperties;
|
||||
import org.signal.i18n.HeaderControlledResourceBundleLookup;
|
||||
@@ -273,6 +275,7 @@ import org.whispersystems.textsecuregcm.workers.BackupMetricsCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.BackupUsageRecalculationCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.CertificateCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.CheckDynamicConfigurationCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.ClearIssuedReceiptRedemptionsCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.DeleteUserCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.IdleDeviceNotificationSchedulerFactory;
|
||||
import org.whispersystems.textsecuregcm.workers.MessagePersisterServiceCommand;
|
||||
@@ -342,6 +345,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
bootstrap.addCommand(new BackupUsageRecalculationCommand());
|
||||
bootstrap.addCommand(new RemoveExpiredLinkedDevicesCommand());
|
||||
bootstrap.addCommand(new NotifyIdleDevicesCommand());
|
||||
bootstrap.addCommand(new ClearIssuedReceiptRedemptionsCommand());
|
||||
|
||||
bootstrap.addCommand(new ProcessScheduledJobsServiceCommand("process-idle-device-notification-jobs",
|
||||
"Processes scheduled jobs to send notifications to idle devices",
|
||||
@@ -381,6 +385,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
dynamicConfigurationManager.start();
|
||||
|
||||
MetricsUtil.configureRegistries(config, environment, dynamicConfigurationManager);
|
||||
MetricsUtil.configureLogging(config, environment);
|
||||
|
||||
ExperimentEnrollmentManager experimentEnrollmentManager = new ExperimentEnrollmentManager(dynamicConfigurationManager);
|
||||
|
||||
@@ -806,7 +811,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
cdn3RemoteStorageManager,
|
||||
svrbCredentialsGenerator,
|
||||
secureValueRecoveryBClient,
|
||||
clock);
|
||||
clock,
|
||||
dynamicConfigurationManager);
|
||||
|
||||
final AppleDeviceChecks appleDeviceChecks = new AppleDeviceChecks(
|
||||
dynamoDbClient,
|
||||
@@ -1139,7 +1145,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
zkReceiptOperations, issuedReceiptsManager);
|
||||
commonControllers.add(new SubscriptionController(clock, config.getSubscription(), config.getOneTimeDonations(),
|
||||
subscriptionManager, stripeManager, braintreeManager, googlePlayBillingManager, appleAppStoreManager,
|
||||
profileBadgeConverter, bankMandateTranslator));
|
||||
profileBadgeConverter, bankMandateTranslator, dynamicConfigurationManager));
|
||||
commonControllers.add(new OneTimeDonationController(clock, config.getOneTimeDonations(), stripeManager, braintreeManager,
|
||||
zkReceiptOperations, issuedReceiptsManager, oneTimeDonationsManager));
|
||||
}
|
||||
@@ -1162,7 +1168,13 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
webSocketEnvironment.jersey().property(ServerProperties.UNWRAP_COMPLETION_STAGE_IN_WRITER_ENABLE, Boolean.TRUE);
|
||||
provisioningEnvironment.jersey().property(ServerProperties.UNWRAP_COMPLETION_STAGE_IN_WRITER_ENABLE, Boolean.TRUE);
|
||||
|
||||
JettyWebSocketServletContainerInitializer.configure(environment.getApplicationContext(), null);
|
||||
JettyWebSocketServletContainerInitializer.configure(environment.getApplicationContext(), (context, container) -> {
|
||||
if (config.getWebSocketConfiguration().isDisablePerMessageDeflate()) {
|
||||
WebSocketComponents components =
|
||||
WebSocketServerComponents.getWebSocketComponents(environment.getApplicationContext().getServletContext());
|
||||
components.getExtensionRegistry().unregister("permessage-deflate");
|
||||
}
|
||||
});
|
||||
|
||||
WebSocketResourceProviderFactory<AuthenticatedDevice> webSocketServlet = new WebSocketResourceProviderFactory<>(
|
||||
webSocketEnvironment, AuthenticatedDevice.class, config.getWebSocketConfiguration(),
|
||||
@@ -1181,8 +1193,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
provisioning.setAsyncSupported(true);
|
||||
|
||||
environment.admin().addTask(new SetRequestLoggingEnabledTask());
|
||||
|
||||
MetricsUtil.registerSystemResourceMetrics(environment);
|
||||
}
|
||||
|
||||
private void registerExceptionMappers(Environment environment,
|
||||
|
||||
@@ -72,6 +72,11 @@ public class OptionalAccess {
|
||||
throw new NotAuthorizedException(Response.Status.UNAUTHORIZED);
|
||||
}
|
||||
|
||||
// Unidentified access is only for ACI identities
|
||||
if (IdentityType.PNI.equals(targetIdentifier.identityType())) {
|
||||
throw new NotAuthorizedException(Response.Status.UNAUTHORIZED);
|
||||
}
|
||||
|
||||
// Unrestricted unidentified access does what it says on the tin: we don't check if the key the
|
||||
// caller provided is right or not.
|
||||
if (targetAccount.get().isUnrestrictedUnidentifiedAccess()) {
|
||||
@@ -82,11 +87,6 @@ public class OptionalAccess {
|
||||
throw new IllegalArgumentException("Target account is not identified by the given identifier");
|
||||
}
|
||||
|
||||
// Unidentified access is only for ACI identities
|
||||
if (IdentityType.PNI.equals(targetIdentifier.identityType())) {
|
||||
throw new NotAuthorizedException(Response.Status.UNAUTHORIZED);
|
||||
}
|
||||
|
||||
// At this point, any successful authentication requires a real access key on the target account
|
||||
if (targetAccount.get().getUnidentifiedAccessKey().isEmpty()) {
|
||||
throw new NotAuthorizedException(Response.Status.UNAUTHORIZED);
|
||||
|
||||
@@ -11,6 +11,8 @@ import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
@@ -31,6 +33,7 @@ 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;
|
||||
@@ -134,6 +137,32 @@ public class BackupAuthManager {
|
||||
.toCompletableFuture();
|
||||
}
|
||||
|
||||
public record BackupIdRotationLimit(boolean hasPermitsRemaining, Duration nextPermitAvailable) {}
|
||||
|
||||
public CompletionStage<BackupIdRotationLimit> checkBackupIdRotationLimit(final Account account) {
|
||||
final RateLimiter messagesLimiter = rateLimiters.forDescriptor(RateLimiters.For.SET_BACKUP_ID);
|
||||
final RateLimiter mediaLimiter = rateLimiters.forDescriptor(RateLimiters.For.SET_PAID_MEDIA_BACKUP_ID);
|
||||
|
||||
final boolean isPaid = hasActiveVoucher(account);
|
||||
|
||||
final CompletionStage<Boolean> hasSetMessagesPermits =
|
||||
messagesLimiter.hasAvailablePermitsAsync(account.getUuid(), 1);
|
||||
final CompletionStage<Boolean> hasSetMediaPermits = isPaid
|
||||
? mediaLimiter.hasAvailablePermitsAsync(account.getUuid(), 1)
|
||||
: CompletableFuture.completedFuture(true);
|
||||
|
||||
return hasSetMessagesPermits.thenCombine(hasSetMediaPermits, (hasMessage, hasMedia) -> {
|
||||
if (hasMedia && hasMessage) {
|
||||
return new BackupIdRotationLimit(true, Duration.ZERO);
|
||||
} else {
|
||||
final Duration timeToNextPermit = Collections.max(Arrays.asList(
|
||||
messagesLimiter.config().permitRegenerationDuration(),
|
||||
isPaid ? mediaLimiter.config().permitRegenerationDuration() : Duration.ZERO));
|
||||
return new BackupIdRotationLimit(false, timeToNextPermit);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public record Credential(BackupAuthCredentialResponse credential, Instant redemptionTime) {}
|
||||
|
||||
/**
|
||||
|
||||
@@ -40,10 +40,13 @@ import org.whispersystems.textsecuregcm.attachments.TusAttachmentGenerator;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedBackupUser;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicBackupConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecoveryClient;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.util.AsyncTimerUtil;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
@@ -57,24 +60,9 @@ import reactor.core.scheduler.Scheduler;
|
||||
public class BackupManager {
|
||||
|
||||
static final String MESSAGE_BACKUP_NAME = "messageBackup";
|
||||
public static final long MAX_TOTAL_BACKUP_MEDIA_BYTES = DataSize.gibibytes(100).toBytes();
|
||||
public static final long MAX_MESSAGE_BACKUP_OBJECT_SIZE = DataSize.mebibytes(101).toBytes();
|
||||
public static final long MAX_MEDIA_OBJECT_SIZE = DataSize.mebibytes(101).toBytes();
|
||||
|
||||
// If the last media usage recalculation is over MAX_QUOTA_STALENESS, force a recalculation before quota enforcement.
|
||||
static final Duration MAX_QUOTA_STALENESS = Duration.ofDays(1);
|
||||
|
||||
// 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;
|
||||
|
||||
// How often we should persist the current usage
|
||||
@VisibleForTesting
|
||||
static int USAGE_CHECKPOINT_COUNT = 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,
|
||||
"authorizationFailure");
|
||||
@@ -85,6 +73,9 @@ public class BackupManager {
|
||||
private static final Timer SYNCHRONOUS_DELETE_TIMER =
|
||||
Metrics.timer(MetricsUtil.name(BackupManager.class, "synchronousDelete"));
|
||||
|
||||
private static final String NUM_OBJECTS_SUMMARY_NAME = MetricsUtil.name(BackupsDb.class, "numObjects");
|
||||
private static final String BYTES_USED_SUMMARY_NAME = MetricsUtil.name(BackupsDb.class, "bytesUsed");
|
||||
|
||||
private static final String SUCCESS_TAG_NAME = "success";
|
||||
private static final String FAILURE_REASON_TAG_NAME = "reason";
|
||||
|
||||
@@ -100,6 +91,7 @@ public class BackupManager {
|
||||
private final ExternalServiceCredentialsGenerator secureValueRecoveryBCredentialsGenerator;
|
||||
private final SecureValueRecoveryClient secureValueRecoveryBClient;
|
||||
private final Clock clock;
|
||||
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
|
||||
|
||||
public BackupManager(
|
||||
final BackupsDb backupsDb,
|
||||
@@ -110,7 +102,8 @@ public class BackupManager {
|
||||
final RemoteStorageManager remoteStorageManager,
|
||||
final ExternalServiceCredentialsGenerator secureValueRecoveryBCredentialsGenerator,
|
||||
final SecureValueRecoveryClient secureValueRecoveryBClient,
|
||||
final Clock clock) {
|
||||
final Clock clock,
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
|
||||
this.backupsDb = backupsDb;
|
||||
this.serverSecretParams = serverSecretParams;
|
||||
this.rateLimiters = rateLimiters;
|
||||
@@ -120,6 +113,7 @@ public class BackupManager {
|
||||
this.secureValueRecoveryBClient = secureValueRecoveryBClient;
|
||||
this.clock = clock;
|
||||
this.secureValueRecoveryBCredentialsGenerator = secureValueRecoveryBCredentialsGenerator;
|
||||
this.dynamicConfigurationManager = dynamicConfigurationManager;
|
||||
}
|
||||
|
||||
|
||||
@@ -156,7 +150,6 @@ public class BackupManager {
|
||||
}));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Create a form that may be used to upload a backup file for the backupId encoded in the presentation.
|
||||
* <p>
|
||||
@@ -173,7 +166,8 @@ public class BackupManager {
|
||||
// this could race with concurrent updates, but the only effect would be last-writer-wins on the timestamp
|
||||
return backupsDb
|
||||
.addMessageBackup(backupUser)
|
||||
.thenApply(result -> cdn3BackupCredentialGenerator.generateUpload(cdnMessageBackupName(backupUser)));
|
||||
.thenApply(_ ->
|
||||
cdn3BackupCredentialGenerator.generateUpload(cdnMessageBackupName(backupUser)));
|
||||
}
|
||||
|
||||
public CompletableFuture<BackupUploadDescriptor> createTemporaryAttachmentUploadDescriptor(
|
||||
@@ -199,7 +193,33 @@ public class BackupManager {
|
||||
public CompletableFuture<Void> ttlRefresh(final AuthenticatedBackupUser backupUser) {
|
||||
checkBackupLevel(backupUser, BackupLevel.FREE);
|
||||
// update message backup TTL
|
||||
return backupsDb.ttlRefresh(backupUser);
|
||||
return backupsDb.ttlRefresh(backupUser).thenAccept(storedBackupAttributes -> {
|
||||
if (backupUser.credentialType() == BackupCredentialType.MEDIA) {
|
||||
final long maxTotalMediaSize =
|
||||
dynamicConfigurationManager.getConfiguration().getBackupConfiguration().maxTotalMediaSize();
|
||||
|
||||
// Report that the backup is out of quota if it cannot store a max size media object
|
||||
final boolean quotaExhausted = storedBackupAttributes.bytesUsed() >=
|
||||
(maxTotalMediaSize - BackupManager.MAX_MEDIA_OBJECT_SIZE);
|
||||
|
||||
final Tags tags = Tags.of(
|
||||
UserAgentTagUtil.getPlatformTag(backupUser.userAgent()),
|
||||
Tag.of("type", backupUser.credentialType().name()),
|
||||
Tag.of("tier", backupUser.backupLevel().name()),
|
||||
Tag.of("quotaExhausted", String.valueOf(quotaExhausted)));
|
||||
|
||||
DistributionSummary.builder(NUM_OBJECTS_SUMMARY_NAME)
|
||||
.tags(tags)
|
||||
.publishPercentileHistogram()
|
||||
.register(Metrics.globalRegistry)
|
||||
.record(storedBackupAttributes.numObjects());
|
||||
DistributionSummary.builder(BYTES_USED_SUMMARY_NAME)
|
||||
.tags(tags)
|
||||
.publishPercentileHistogram()
|
||||
.register(Metrics.globalRegistry)
|
||||
.record(storedBackupAttributes.bytesUsed());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public record BackupInfo(int cdn, String backupSubdir, String mediaSubdir, String messageBackupKey,
|
||||
@@ -238,6 +258,9 @@ public class BackupManager {
|
||||
checkBackupLevel(backupUser, BackupLevel.PAID);
|
||||
checkBackupCredentialType(backupUser, BackupCredentialType.MEDIA);
|
||||
|
||||
final DynamicBackupConfiguration backupConfiguration =
|
||||
dynamicConfigurationManager.getConfiguration().getBackupConfiguration();
|
||||
|
||||
return Mono.fromFuture(() -> allowedCopies(backupUser, toCopy))
|
||||
.flatMapMany(quotaResult -> Flux.concat(
|
||||
|
||||
@@ -247,7 +270,7 @@ public class BackupManager {
|
||||
Flux.fromIterable(quotaResult.requestsToCopy())
|
||||
|
||||
// Update the usage in reasonable chunk sizes to bound how out of sync our claimed and actual usage gets
|
||||
.buffer(USAGE_CHECKPOINT_COUNT)
|
||||
.buffer(backupConfiguration.usageCheckpointCount())
|
||||
.concatMap(copyParameters -> {
|
||||
final long quotaToConsume = copyParameters.stream()
|
||||
.mapToLong(CopyParameters::destinationObjectSize)
|
||||
@@ -265,7 +288,7 @@ public class BackupManager {
|
||||
.fromFuture(this.backupsDb.trackMedia(backupUser, -1, -copyParams.destinationObjectSize()))
|
||||
.thenReturn(copyResult);
|
||||
}),
|
||||
COPY_CONCURRENCY, 1),
|
||||
backupConfiguration.copyConcurrency(), 1),
|
||||
|
||||
// There wasn't enough quota remaining to perform these copies
|
||||
Flux.fromIterable(quotaResult.requestsToReject())
|
||||
@@ -317,11 +340,16 @@ public class BackupManager {
|
||||
})
|
||||
.sum();
|
||||
|
||||
final DynamicBackupConfiguration backupConfiguration =
|
||||
dynamicConfigurationManager.getConfiguration().getBackupConfiguration();
|
||||
final Duration maxQuotaStaleness = backupConfiguration.maxQuotaStaleness();
|
||||
final long maxTotalMediaSize = backupConfiguration.maxTotalMediaSize();
|
||||
|
||||
return backupsDb.getMediaUsage(backupUser)
|
||||
.thenComposeAsync(info -> {
|
||||
long remainingQuota = MAX_TOTAL_BACKUP_MEDIA_BYTES - info.usageInfo().bytesUsed();
|
||||
long remainingQuota = maxTotalMediaSize - info.usageInfo().bytesUsed();
|
||||
final boolean canStore = remainingQuota >= totalBytesAdded;
|
||||
if (canStore || info.lastRecalculationTime().isAfter(clock.instant().minus(MAX_QUOTA_STALENESS))) {
|
||||
if (canStore || info.lastRecalculationTime().isAfter(clock.instant().minus(maxQuotaStaleness))) {
|
||||
return CompletableFuture.completedFuture(remainingQuota);
|
||||
}
|
||||
|
||||
@@ -338,7 +366,7 @@ public class BackupManager {
|
||||
Tag.of("usageChanged", String.valueOf(usageChanged))))
|
||||
.increment();
|
||||
})
|
||||
.thenApply(newUsage -> MAX_TOTAL_BACKUP_MEDIA_BYTES - newUsage.bytesUsed());
|
||||
.thenApply(newUsage -> maxTotalMediaSize - newUsage.bytesUsed());
|
||||
})
|
||||
.thenApply(remainingQuota -> {
|
||||
// Figure out how many of the requested objects fit in the remaining quota
|
||||
@@ -456,6 +484,9 @@ public class BackupManager {
|
||||
public CompletableFuture<Void> deleteEntireBackup(final AuthenticatedBackupUser backupUser) {
|
||||
checkBackupLevel(backupUser, BackupLevel.FREE);
|
||||
|
||||
final int deletionConcurrency =
|
||||
dynamicConfigurationManager.getConfiguration().getBackupConfiguration().deletionConcurrency();
|
||||
|
||||
// Clients only include SVRB data with their messages backup-id
|
||||
final CompletableFuture<Void> svrbRemoval = switch(backupUser.credentialType()) {
|
||||
case BackupCredentialType.MESSAGES -> secureValueRecoveryBClient.removeData(svrbIdentifier(backupUser));
|
||||
@@ -467,7 +498,7 @@ public class BackupManager {
|
||||
// If there was already a pending swap, try to delete the cdn objects directly
|
||||
.exceptionallyCompose(ExceptionUtils.exceptionallyHandler(BackupsDb.PendingDeletionException.class, e ->
|
||||
AsyncTimerUtil.record(SYNCHRONOUS_DELETE_TIMER, () ->
|
||||
deletePrefix(backupUser.backupDir(), DELETION_CONCURRENCY)))));
|
||||
deletePrefix(backupUser.backupDir(), deletionConcurrency)))));
|
||||
}
|
||||
|
||||
|
||||
@@ -482,11 +513,13 @@ public class BackupManager {
|
||||
.withDescription("unsupported media cdn provided")
|
||||
.asRuntimeException();
|
||||
}
|
||||
final DynamicBackupConfiguration backupConfiguration =
|
||||
dynamicConfigurationManager.getConfiguration().getBackupConfiguration();
|
||||
|
||||
return Flux.usingWhen(
|
||||
|
||||
// Gather usage updates into the UsageBatcher so we don't have to update our backup record on every delete
|
||||
Mono.just(new UsageBatcher()),
|
||||
Mono.just(new UsageBatcher(backupConfiguration.usageCheckpointCount())),
|
||||
|
||||
// Deletes the objects, returning their former location. Tracks bytes removed so the quota can be updated on
|
||||
// completion
|
||||
@@ -495,7 +528,7 @@ public class BackupManager {
|
||||
// Delete the objects, allowing DELETION_CONCURRENCY operations out at a time
|
||||
.flatMapSequential(
|
||||
sd -> Mono.fromCompletionStage(remoteStorageManager.delete(cdnMediaPath(backupUser, sd.key()))),
|
||||
DELETION_CONCURRENCY)
|
||||
backupConfiguration.deletionConcurrency())
|
||||
.zipWithIterable(storageDescriptors)
|
||||
|
||||
// Track how much the remote storage manager indicated was deleted as part of the operation
|
||||
@@ -531,9 +564,14 @@ public class BackupManager {
|
||||
*/
|
||||
private static class UsageBatcher {
|
||||
|
||||
private final int usageCheckpointCount;
|
||||
private long runningCountDelta = 0;
|
||||
private long runningBytesDelta = 0;
|
||||
|
||||
UsageBatcher(int usageCheckpointCount) {
|
||||
this.usageCheckpointCount = usageCheckpointCount;
|
||||
}
|
||||
|
||||
record UsageUpdate(long countDelta, long bytesDelta) {}
|
||||
|
||||
/**
|
||||
@@ -546,7 +584,7 @@ public class BackupManager {
|
||||
boolean update(long bytesDelta) {
|
||||
this.runningCountDelta += Long.signum(bytesDelta);
|
||||
this.runningBytesDelta += bytesDelta;
|
||||
return Math.abs(runningCountDelta) >= USAGE_CHECKPOINT_COUNT;
|
||||
return Math.abs(runningCountDelta) >= usageCheckpointCount;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -622,11 +660,10 @@ public class BackupManager {
|
||||
* List all backups stored in the backups table
|
||||
*
|
||||
* @param segments Number of segments to read in parallel from the underlying backup database
|
||||
* @param scheduler Scheduler for running downstream operations
|
||||
* @return Flux of {@link StoredBackupAttributes} for each backup record in the backups table
|
||||
*/
|
||||
public Flux<StoredBackupAttributes> listBackupAttributes(final int segments, final Scheduler scheduler) {
|
||||
return this.backupsDb.listBackupAttributes(segments, scheduler);
|
||||
public Flux<StoredBackupAttributes> listBackupAttributes(final int segments) {
|
||||
return this.backupsDb.listBackupAttributes(segments);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -87,10 +87,6 @@ public class BackupsDb {
|
||||
|
||||
private final SecureRandom secureRandom;
|
||||
|
||||
private static final String NUM_OBJECTS_SUMMARY_NAME = MetricsUtil.name(BackupsDb.class, "numObjects");
|
||||
private static final String BYTES_USED_SUMMARY_NAME = MetricsUtil.name(BackupsDb.class, "bytesUsed");
|
||||
private static final String BACKUPS_COUNTER_NAME = MetricsUtil.name(BackupsDb.class, "backups");
|
||||
|
||||
// The backups table
|
||||
|
||||
// B: 16 bytes that identifies the backup
|
||||
@@ -246,7 +242,7 @@ public class BackupsDb {
|
||||
*
|
||||
* @param backupUser an already authorized backup user
|
||||
*/
|
||||
CompletableFuture<Void> ttlRefresh(final AuthenticatedBackupUser backupUser) {
|
||||
CompletableFuture<StoredBackupAttributes> ttlRefresh(final AuthenticatedBackupUser backupUser) {
|
||||
final Instant today = clock.instant().truncatedTo(ChronoUnit.DAYS);
|
||||
// update message backup TTL
|
||||
return dynamoClient.updateItem(UpdateBuilder.forUser(backupTableName, backupUser)
|
||||
@@ -254,16 +250,17 @@ public class BackupsDb {
|
||||
.updateItemBuilder()
|
||||
.returnValues(ReturnValue.ALL_OLD)
|
||||
.build())
|
||||
.thenAccept(updateItemResponse ->
|
||||
updateMetricsAfterRefresh(backupUser, today, updateItemResponse.attributes()));
|
||||
.thenApply(updateItemResponse -> fromItem(updateItemResponse.attributes()));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Track that a backup will be stored for the user
|
||||
*
|
||||
* @param backupUser an already authorized backup user
|
||||
* @return A future that completes with the attributes of the backup before the update
|
||||
*/
|
||||
CompletableFuture<Void> addMessageBackup(final AuthenticatedBackupUser backupUser) {
|
||||
CompletableFuture<StoredBackupAttributes> addMessageBackup(final AuthenticatedBackupUser backupUser) {
|
||||
final Instant today = clock.instant().truncatedTo(ChronoUnit.DAYS);
|
||||
// this could race with concurrent updates, but the only effect would be last-writer-wins on the timestamp
|
||||
return dynamoClient.updateItem(
|
||||
@@ -273,40 +270,7 @@ public class BackupsDb {
|
||||
.updateItemBuilder()
|
||||
.returnValues(ReturnValue.ALL_OLD)
|
||||
.build())
|
||||
.thenAccept(updateItemResponse ->
|
||||
updateMetricsAfterRefresh(backupUser, today, updateItemResponse.attributes()));
|
||||
}
|
||||
|
||||
private void updateMetricsAfterRefresh(final AuthenticatedBackupUser backupUser, final Instant today, final Map<String, AttributeValue> item) {
|
||||
final Instant previousRefreshTime = Instant.ofEpochSecond(
|
||||
AttributeValues.getLong(item, ATTR_LAST_REFRESH, 0L));
|
||||
// Only publish a metric update once per day
|
||||
if (previousRefreshTime.isBefore(today)) {
|
||||
final long mediaCount = AttributeValues.getLong(item, ATTR_MEDIA_COUNT, 0L);
|
||||
final long bytesUsed = AttributeValues.getLong(item, ATTR_MEDIA_BYTES_USED, 0L);
|
||||
final Tags tags = Tags.of(
|
||||
UserAgentTagUtil.getPlatformTag(backupUser.userAgent()),
|
||||
Tag.of("tier", backupUser.backupLevel().name()));
|
||||
|
||||
DistributionSummary.builder(NUM_OBJECTS_SUMMARY_NAME)
|
||||
.tags(tags)
|
||||
.publishPercentileHistogram()
|
||||
.register(Metrics.globalRegistry)
|
||||
.record(mediaCount);
|
||||
DistributionSummary.builder(BYTES_USED_SUMMARY_NAME)
|
||||
.tags(tags)
|
||||
.publishPercentileHistogram()
|
||||
.register(Metrics.globalRegistry)
|
||||
.record(bytesUsed);
|
||||
|
||||
// Report that the backup is out of quota if it cannot store a max size media object
|
||||
final boolean quotaExhausted = bytesUsed >=
|
||||
(BackupManager.MAX_TOTAL_BACKUP_MEDIA_BYTES - BackupManager.MAX_MEDIA_OBJECT_SIZE);
|
||||
|
||||
Metrics.counter(BACKUPS_COUNTER_NAME,
|
||||
tags.and("quotaExhausted", String.valueOf(quotaExhausted)))
|
||||
.increment();
|
||||
}
|
||||
.thenApply(updateItemResponse -> fromItem(updateItemResponse.attributes()));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -497,14 +461,12 @@ public class BackupsDb {
|
||||
}
|
||||
}
|
||||
|
||||
Flux<StoredBackupAttributes> listBackupAttributes(final int segments, final Scheduler scheduler) {
|
||||
Flux<StoredBackupAttributes> listBackupAttributes(final int segments) {
|
||||
if (segments < 1) {
|
||||
throw new IllegalArgumentException("Total number of segments must be positive");
|
||||
}
|
||||
|
||||
return Flux.range(0, segments)
|
||||
.parallel()
|
||||
.runOn(scheduler)
|
||||
.flatMap(segment -> dynamoClient.scanPaginator(ScanRequest.builder()
|
||||
.tableName(backupTableName)
|
||||
.consistentRead(true)
|
||||
@@ -519,18 +481,22 @@ public class BackupsDb {
|
||||
"#backupDir", ATTR_BACKUP_DIR,
|
||||
"#mediaDir", ATTR_MEDIA_DIR))
|
||||
.projectionExpression("#backupIdHash, #refresh, #mediaRefresh, #bytesUsed, #numObjects, #backupDir, #mediaDir")
|
||||
.build())
|
||||
.items())
|
||||
.sequential()
|
||||
.build()))
|
||||
// Don't use the SDK's item publisher, works around https://github.com/aws/aws-sdk-java-v2/issues/6411
|
||||
.concatMap(page -> Flux.fromIterable(page.items()))
|
||||
.filter(item -> item.containsKey(KEY_BACKUP_ID_HASH))
|
||||
.map(item -> new StoredBackupAttributes(
|
||||
AttributeValues.getByteArray(item, KEY_BACKUP_ID_HASH, null),
|
||||
AttributeValues.getString(item, ATTR_BACKUP_DIR, null),
|
||||
AttributeValues.getString(item, ATTR_MEDIA_DIR, null),
|
||||
Instant.ofEpochSecond(AttributeValues.getLong(item, ATTR_LAST_REFRESH, 0L)),
|
||||
Instant.ofEpochSecond(AttributeValues.getLong(item, ATTR_LAST_MEDIA_REFRESH, 0L)),
|
||||
AttributeValues.getLong(item, ATTR_MEDIA_BYTES_USED, 0L),
|
||||
AttributeValues.getLong(item, ATTR_MEDIA_COUNT, 0L)));
|
||||
.map(BackupsDb::fromItem);
|
||||
}
|
||||
|
||||
private static StoredBackupAttributes fromItem(Map<String, AttributeValue> item) {
|
||||
return new StoredBackupAttributes(
|
||||
AttributeValues.getByteArray(item, KEY_BACKUP_ID_HASH, null),
|
||||
AttributeValues.getString(item, ATTR_BACKUP_DIR, null),
|
||||
AttributeValues.getString(item, ATTR_MEDIA_DIR, null),
|
||||
Instant.ofEpochSecond(AttributeValues.getLong(item, ATTR_LAST_REFRESH, 0L)),
|
||||
Instant.ofEpochSecond(AttributeValues.getLong(item, ATTR_LAST_MEDIA_REFRESH, 0L)),
|
||||
AttributeValues.getLong(item, ATTR_MEDIA_BYTES_USED, 0L),
|
||||
AttributeValues.getLong(item, ATTR_MEDIA_COUNT, 0L));
|
||||
}
|
||||
|
||||
Flux<ExpiredBackup> getExpiredBackups(final int segments, final Scheduler scheduler, final Instant purgeTime) {
|
||||
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration.dynamic;
|
||||
|
||||
import io.dropwizard.util.DataSize;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import java.time.Duration;
|
||||
|
||||
/**
|
||||
*
|
||||
* @param deletionConcurrency How many cdn object deletion requests can be outstanding at a time per backup deletion operation
|
||||
* @param copyConcurrency How many cdn object copy requests can be outstanding at a time per batch copy-to-backup operation
|
||||
* @param usageCheckpointCount When doing batch operations, how often persist usage deltas
|
||||
* @param maxQuotaStaleness The maximum age of a quota estimate that can be used to enforce a quota limit
|
||||
* @param maxTotalMediaSize The number of media bytes a paid-tier user may store
|
||||
*/
|
||||
public record DynamicBackupConfiguration(
|
||||
@NotNull Integer deletionConcurrency,
|
||||
@NotNull Integer copyConcurrency,
|
||||
@NotNull Integer usageCheckpointCount,
|
||||
@NotNull Duration maxQuotaStaleness,
|
||||
@NotNull Long maxTotalMediaSize) {
|
||||
|
||||
public DynamicBackupConfiguration {
|
||||
if (deletionConcurrency == null) {
|
||||
deletionConcurrency = 10;
|
||||
}
|
||||
if (copyConcurrency == null) {
|
||||
copyConcurrency = 10;
|
||||
}
|
||||
if (usageCheckpointCount == null) {
|
||||
usageCheckpointCount = 10;
|
||||
}
|
||||
if (maxQuotaStaleness == null) {
|
||||
maxQuotaStaleness = Duration.ofDays(1);
|
||||
}
|
||||
if (maxTotalMediaSize == null) {
|
||||
maxTotalMediaSize = DataSize.gibibytes(100).toBytes();
|
||||
}
|
||||
}
|
||||
|
||||
public DynamicBackupConfiguration() {
|
||||
this(null, null, null, null, null);
|
||||
}
|
||||
}
|
||||
+8
-1
@@ -50,7 +50,7 @@ public class DynamicConfiguration {
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
DynamicMetricsConfiguration metricsConfiguration = new DynamicMetricsConfiguration(false, false);
|
||||
DynamicMetricsConfiguration metricsConfiguration = new DynamicMetricsConfiguration(false, false, null);
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
@@ -64,6 +64,10 @@ public class DynamicConfiguration {
|
||||
@Valid
|
||||
DynamicRestDeprecationConfiguration restDeprecation = new DynamicRestDeprecationConfiguration(Map.of());
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
private DynamicBackupConfiguration backup = new DynamicBackupConfiguration();
|
||||
|
||||
public Optional<DynamicExperimentEnrollmentConfiguration> getExperimentEnrollmentConfiguration(
|
||||
final String experimentName) {
|
||||
return Optional.ofNullable(experiments.get(experimentName));
|
||||
@@ -114,4 +118,7 @@ public class DynamicConfiguration {
|
||||
return restDeprecation;
|
||||
}
|
||||
|
||||
public DynamicBackupConfiguration getBackupConfiguration() {
|
||||
return backup;
|
||||
}
|
||||
}
|
||||
+5
-1
@@ -5,11 +5,15 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration.dynamic;
|
||||
|
||||
import java.util.Set;
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
/**
|
||||
* @param enableLettuceRemoteTag whether the `remote` tag should be added. Note: although this is dynamic, meters are
|
||||
* cached after creation, so changes will only affect servers launched after the change.
|
||||
* @param enableAwsSdkMetrics whether to record AWS SDK metrics. Note: although this is dynamic, meters are cached after
|
||||
* creation, so changes will only affect servers launched after the change.
|
||||
* @param datadogAllowList if present, a list of metrics to send to datadog; others will be filtered out. If null, this filtering is not performed.
|
||||
*/
|
||||
public record DynamicMetricsConfiguration(boolean enableLettuceRemoteTag, boolean enableAwsSdkMetrics) {
|
||||
public record DynamicMetricsConfiguration(boolean enableLettuceRemoteTag, boolean enableAwsSdkMetrics, @Nullable Set<String> datadogAllowList) {
|
||||
}
|
||||
+28
@@ -163,6 +163,34 @@ public class ArchiveController {
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
public record BackupIdLimitResponse(
|
||||
@Schema(description = "If true, a call to PUT /v1/archive/backupid may succeed without waiting")
|
||||
boolean hasPermitsRemaining,
|
||||
@Schema(description = "How long to wait before a permit becomes available, in seconds")
|
||||
long retryAfterSeconds) {}
|
||||
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/backupid/limits")
|
||||
@Operation(
|
||||
summary = "Retrieve limits",
|
||||
description = """
|
||||
Determine whether the backup-id can currently be rotated
|
||||
""")
|
||||
@ApiResponse(responseCode = "200", description = "Successfully retrieved backup-id rotation limits", useReturnTypeSchema = true)
|
||||
@ApiResponse(responseCode = "403", description = "Invalid account authentication")
|
||||
public CompletionStage<BackupIdLimitResponse> checkLimits(@Auth final AuthenticatedDevice authenticatedDevice) {
|
||||
return accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier())
|
||||
.thenCompose(maybeAccount -> {
|
||||
final Account account = maybeAccount
|
||||
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
|
||||
|
||||
return backupAuthManager.checkBackupIdRotationLimit(account).thenApply(limit ->
|
||||
new BackupIdLimitResponse(limit.hasPermitsRemaining(), limit.nextPermitAvailable().getSeconds()));
|
||||
});
|
||||
}
|
||||
|
||||
public record RedeemBackupReceiptRequest(
|
||||
@Schema(description = "Presentation of a ZK receipt encoded in standard padded base64", implementation = String.class)
|
||||
@JsonDeserialize(using = Deserializer.class)
|
||||
|
||||
+9
-2
@@ -65,11 +65,13 @@ import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfigurati
|
||||
import org.whispersystems.textsecuregcm.configuration.OneTimeDonationCurrencyConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.SubscriptionConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.SubscriptionLevelConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.entities.Badge;
|
||||
import org.whispersystems.textsecuregcm.entities.PurchasableBadge;
|
||||
import org.whispersystems.textsecuregcm.mappers.SubscriptionExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.storage.PaymentTime;
|
||||
import org.whispersystems.textsecuregcm.storage.SubscriberCredentials;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionException;
|
||||
@@ -109,6 +111,7 @@ public class SubscriptionController {
|
||||
private final AppleAppStoreManager appleAppStoreManager;
|
||||
private final BadgeTranslator badgeTranslator;
|
||||
private final BankMandateTranslator bankMandateTranslator;
|
||||
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
|
||||
static final String RECEIPT_ISSUED_COUNTER_NAME = MetricsUtil.name(SubscriptionController.class, "receiptIssued");
|
||||
static final String PROCESSOR_TAG_NAME = "processor";
|
||||
static final String TYPE_TAG_NAME = "type";
|
||||
@@ -124,7 +127,8 @@ public class SubscriptionController {
|
||||
@Nonnull GooglePlayBillingManager googlePlayBillingManager,
|
||||
@Nonnull AppleAppStoreManager appleAppStoreManager,
|
||||
@Nonnull BadgeTranslator badgeTranslator,
|
||||
@Nonnull BankMandateTranslator bankMandateTranslator) {
|
||||
@Nonnull BankMandateTranslator bankMandateTranslator,
|
||||
@NotNull DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
|
||||
this.subscriptionManager = subscriptionManager;
|
||||
this.clock = Objects.requireNonNull(clock);
|
||||
this.subscriptionConfiguration = Objects.requireNonNull(subscriptionConfiguration);
|
||||
@@ -135,6 +139,7 @@ public class SubscriptionController {
|
||||
this.appleAppStoreManager = appleAppStoreManager;
|
||||
this.badgeTranslator = Objects.requireNonNull(badgeTranslator);
|
||||
this.bankMandateTranslator = Objects.requireNonNull(bankMandateTranslator);
|
||||
this.dynamicConfigurationManager = dynamicConfigurationManager;
|
||||
}
|
||||
|
||||
private Map<String, CurrencyConfiguration> buildCurrencyConfiguration() {
|
||||
@@ -207,12 +212,14 @@ public class SubscriptionController {
|
||||
giftBadge,
|
||||
oneTimeDonationConfiguration.gift().expiration())));
|
||||
|
||||
final long maxTotalBackupMediaBytes =
|
||||
dynamicConfigurationManager.getConfiguration().getBackupConfiguration().maxTotalMediaSize();
|
||||
final Map<String, BackupLevelConfiguration> backupLevels = subscriptionConfiguration.getBackupLevels()
|
||||
.entrySet().stream()
|
||||
.collect(Collectors.toMap(
|
||||
e -> String.valueOf(e.getKey()),
|
||||
e -> new BackupLevelConfiguration(
|
||||
BackupManager.MAX_TOTAL_BACKUP_MEDIA_BYTES,
|
||||
maxTotalBackupMediaBytes,
|
||||
e.getValue().playProductId(),
|
||||
e.getValue().mediaTtl().toDays())));
|
||||
|
||||
|
||||
+3
@@ -89,6 +89,9 @@ public record RegistrationRequest(@Schema(requiredMode = Schema.RequiredMode.NOT
|
||||
@AssertTrue
|
||||
@Schema(hidden = true)
|
||||
boolean hasExactlyOneMessageDeliveryChannel() {
|
||||
if (deviceActivationRequest == null || accountAttributes == null) {
|
||||
return false;
|
||||
}
|
||||
if (accountAttributes.getFetchesMessages()) {
|
||||
return deviceActivationRequest().apnToken().isEmpty() && deviceActivationRequest().gcmToken().isEmpty();
|
||||
} else {
|
||||
|
||||
@@ -44,7 +44,7 @@ public abstract class BaseRateLimiters<T extends RateLimiterDescriptor> {
|
||||
return requireNonNull(rateLimiterByDescriptor.get(handle));
|
||||
}
|
||||
|
||||
protected static ClusterLuaScript defaultScript(final FaultTolerantRedisClusterClient cacheCluster) {
|
||||
public static ClusterLuaScript defaultScript(final FaultTolerantRedisClusterClient cacheCluster) {
|
||||
try {
|
||||
return ClusterLuaScript.fromResource(
|
||||
cacheCluster, "lua/validate_rate_limit.lua", ScriptOutputType.INTEGER);
|
||||
|
||||
+13
-5
@@ -12,6 +12,10 @@ import io.micrometer.core.instrument.MeterRegistry;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import javax.annotation.Nullable;
|
||||
import org.glassfish.jersey.server.ContainerResponse;
|
||||
import org.glassfish.jersey.server.monitoring.RequestEvent;
|
||||
import org.glassfish.jersey.server.monitoring.RequestEventListener;
|
||||
@@ -21,11 +25,6 @@ import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
|
||||
import org.whispersystems.textsecuregcm.util.logging.UriInfoUtil;
|
||||
import org.whispersystems.websocket.WebSocketResourceProvider;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Gathers and reports request-level metrics for WebSocket traffic only.
|
||||
* For HTTP traffic, use {@link MetricsHttpChannelListener}.
|
||||
@@ -53,6 +52,9 @@ public class MetricsRequestEventListener implements RequestEventListener {
|
||||
@VisibleForTesting
|
||||
static final String TRAFFIC_SOURCE_TAG = "trafficSource";
|
||||
|
||||
@VisibleForTesting
|
||||
static final String AUTHENTICATED_TAG = "authenticated";
|
||||
|
||||
private final TrafficSource trafficSource;
|
||||
private final MeterRegistry meterRegistry;
|
||||
|
||||
@@ -86,6 +88,12 @@ public class MetricsRequestEventListener implements RequestEventListener {
|
||||
.map(ContainerResponse::getStatus)
|
||||
.orElse(499))));
|
||||
tags.add(Tag.of(TRAFFIC_SOURCE_TAG, trafficSource.name().toLowerCase()));
|
||||
tags.add(Tag.of(AUTHENTICATED_TAG, Optional.ofNullable(event.getContainerRequest().getProperty(WebSocketResourceProvider.REUSABLE_AUTH_PROPERTY))
|
||||
.filter(Optional.class::isInstance)
|
||||
.map(Optional.class::cast)
|
||||
.map(Optional::isPresent)
|
||||
.orElse(false)
|
||||
.toString()));
|
||||
|
||||
@Nullable final String userAgent;
|
||||
{
|
||||
|
||||
@@ -8,6 +8,7 @@ package org.whispersystems.textsecuregcm.metrics;
|
||||
import com.codahale.metrics.SharedMetricRegistries;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.dropwizard.core.setup.Environment;
|
||||
import io.dropwizard.lifecycle.Managed;
|
||||
import io.micrometer.core.instrument.Meter;
|
||||
import io.micrometer.core.instrument.MeterRegistry;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
@@ -21,7 +22,18 @@ import io.micrometer.core.instrument.config.MeterFilter;
|
||||
import io.micrometer.core.instrument.distribution.DistributionStatisticConfig;
|
||||
import io.micrometer.registry.otlp.OtlpMeterRegistry;
|
||||
import io.micrometer.statsd.StatsdMeterRegistry;
|
||||
import io.opentelemetry.exporter.otlp.http.logs.OtlpHttpLogRecordExporter;
|
||||
import io.opentelemetry.instrumentation.logback.appender.v1_0.OpenTelemetryAppender;
|
||||
import io.opentelemetry.sdk.OpenTelemetrySdk;
|
||||
import io.opentelemetry.sdk.logs.SdkLoggerProvider;
|
||||
import io.opentelemetry.sdk.logs.export.BatchLogRecordProcessor;
|
||||
import io.opentelemetry.sdk.resources.Resource;
|
||||
import io.opentelemetry.sdk.resources.ResourceBuilder;
|
||||
import io.opentelemetry.semconv.ServiceAttributes;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.WhisperServerVersion;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
@@ -74,6 +86,7 @@ public class MetricsUtil {
|
||||
"env", config.getDatadogConfiguration().getEnvironment()));
|
||||
|
||||
configureMeterFilters(dogstatsdMeterRegistry.config(), dynamicConfigurationManager);
|
||||
configureDatadogAllowList(dogstatsdMeterRegistry.config(), dynamicConfigurationManager);
|
||||
Metrics.addRegistry(dogstatsdMeterRegistry);
|
||||
|
||||
shutdownWaitDuration = config.getDatadogConfiguration().getShutdownWaitDuration();
|
||||
@@ -97,6 +110,46 @@ public class MetricsUtil {
|
||||
environment.lifecycle().addEventListener(new ApplicationShutdownMonitor(Metrics.globalRegistry));
|
||||
environment.lifecycle().addEventListener(
|
||||
new MicrometerRegistryManager(Metrics.globalRegistry, shutdownWaitDuration));
|
||||
|
||||
registerSystemResourceMetrics();
|
||||
}
|
||||
|
||||
public static void configureLogging(final WhisperServerConfiguration config, final Environment environment) {
|
||||
if (!config.getOpenTelemetryConfiguration().enabled()) {
|
||||
return;
|
||||
}
|
||||
|
||||
final Map<String, String> env = System.getenv();
|
||||
final String endpoint =
|
||||
Optional.ofNullable(env.get("OTEL_EXPORTER_OTLP_LOGS_ENDPOINT"))
|
||||
.or(() -> Optional.ofNullable(env.get("OTEL_EXPORTER_OTLP_ENDPOINT")))
|
||||
.map(u -> u.endsWith("/v1/logs") ? u : u + "/v1/logs")
|
||||
.orElse("http://localhost:4318/v1/logs");
|
||||
|
||||
final ResourceBuilder resource = Resource.builder();
|
||||
config.getOpenTelemetryConfiguration().resourceAttributes().forEach((k, v) -> resource.put(k, v));
|
||||
|
||||
final OpenTelemetrySdk openTelemetry =
|
||||
OpenTelemetrySdk.builder()
|
||||
.setLoggerProvider(
|
||||
SdkLoggerProvider.builder()
|
||||
.setResource(resource.build())
|
||||
.addLogRecordProcessor(
|
||||
BatchLogRecordProcessor.builder(
|
||||
OtlpHttpLogRecordExporter.builder()
|
||||
.setEndpoint(endpoint)
|
||||
.build()).build())
|
||||
.build())
|
||||
.build();
|
||||
|
||||
OpenTelemetryAppender.install(openTelemetry);
|
||||
|
||||
environment.lifecycle().manage(new Managed() {
|
||||
@Override
|
||||
public void stop() {
|
||||
openTelemetry.shutdown();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
@@ -136,7 +189,15 @@ public class MetricsUtil {
|
||||
&& id.getName().startsWith(awsSdkMetricNamePrefix)));
|
||||
}
|
||||
|
||||
public static void registerSystemResourceMetrics(final Environment environment) {
|
||||
@VisibleForTesting
|
||||
static void configureDatadogAllowList(
|
||||
final MeterRegistry.Config config, final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
|
||||
config.meterFilter(MeterFilter.denyUnless(id ->
|
||||
dynamicConfigurationManager.getConfiguration().getMetricsConfiguration().datadogAllowList() == null ||
|
||||
dynamicConfigurationManager.getConfiguration().getMetricsConfiguration().datadogAllowList().contains(id.getName())));
|
||||
}
|
||||
|
||||
static void registerSystemResourceMetrics() {
|
||||
new ProcessorMetrics().bindTo(Metrics.globalRegistry);
|
||||
new FileDescriptorMetrics().bindTo(Metrics.globalRegistry);
|
||||
|
||||
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.metrics;
|
||||
|
||||
import ch.qos.logback.classic.LoggerContext;
|
||||
import ch.qos.logback.classic.spi.ILoggingEvent;
|
||||
import ch.qos.logback.core.Appender;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.annotation.JsonTypeName;
|
||||
import io.dropwizard.logging.common.AbstractAppenderFactory;
|
||||
import io.dropwizard.logging.common.async.AsyncAppenderFactory;
|
||||
import io.dropwizard.logging.common.filter.LevelFilterFactory;
|
||||
import io.dropwizard.logging.common.layout.LayoutFactory;
|
||||
import io.opentelemetry.instrumentation.logback.appender.v1_0.OpenTelemetryAppender;
|
||||
|
||||
@JsonTypeName("otlp")
|
||||
public class OpenTelemetryAppenderFactory extends AbstractAppenderFactory<ILoggingEvent> {
|
||||
|
||||
@JsonProperty
|
||||
private String destination;
|
||||
|
||||
@Override
|
||||
public Appender<ILoggingEvent> build(
|
||||
final LoggerContext context,
|
||||
final String applicationName,
|
||||
final LayoutFactory<ILoggingEvent> layoutFactory,
|
||||
final LevelFilterFactory<ILoggingEvent> levelFilterFactory,
|
||||
final AsyncAppenderFactory<ILoggingEvent> asyncAppenderFactory) {
|
||||
|
||||
final OpenTelemetryAppender appender = new OpenTelemetryAppender();
|
||||
appender.setCaptureCodeAttributes(true);
|
||||
appender.setCaptureLoggerContext(true);
|
||||
|
||||
// The installation of an OpenTelemetry configuration happens in
|
||||
// WhisperServerService (or CommandDependencies), in order to let us tie
|
||||
// into Dropwizard's lifecycle management; this allows us to buffer any
|
||||
// logs emitted between now and that happening.
|
||||
appender.setNumLogsCapturedBeforeOtelInstall(1000);
|
||||
|
||||
appender.addFilter(levelFilterFactory.build(threshold));
|
||||
getFilterFactories().forEach(f -> appender.addFilter(f.build()));
|
||||
appender.start();
|
||||
|
||||
return wrapAsync(appender, asyncAppenderFactory);
|
||||
}
|
||||
}
|
||||
+19
@@ -34,6 +34,7 @@ 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.ConditionalCheckFailedException;
|
||||
import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ReturnValue;
|
||||
import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest;
|
||||
|
||||
@@ -109,6 +110,24 @@ public class IssuedReceiptsManager {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear the recorded issuances for a particular item
|
||||
*
|
||||
* @param processorItemId The itemId within the processor to clear
|
||||
* @param processor The processor
|
||||
* @return a future that yields true if the item was deleted, false if the item already did not exist
|
||||
*/
|
||||
public CompletableFuture<Boolean> clearIssuance(String processorItemId, PaymentProvider processor) {
|
||||
final AttributeValue key = dynamoDbKey(processor, processorItemId);
|
||||
final DeleteItemRequest deleteItemRequest = DeleteItemRequest.builder()
|
||||
.tableName(table)
|
||||
.key(Map.of(KEY_PROCESSOR_ITEM_ID, key))
|
||||
.returnValues(ReturnValue.ALL_OLD)
|
||||
.build();
|
||||
return dynamoDbAsyncClient.deleteItem(deleteItemRequest)
|
||||
.thenApply(item -> item.hasAttributes() && !item.attributes().isEmpty());
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static AttributeValue dynamoDbKey(final PaymentProvider processor, String processorItemId) {
|
||||
if (processor == PaymentProvider.STRIPE) {
|
||||
|
||||
+1
@@ -220,6 +220,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
.setAmount(amount)
|
||||
.setCurrency(currency.toLowerCase(Locale.ROOT))
|
||||
.setDescription(boostDescription)
|
||||
.setCaptureMethod(PaymentIntentCreateParams.CaptureMethod.AUTOMATIC)
|
||||
.putMetadata("level", Long.toString(level));
|
||||
|
||||
if (clientPlatform != null) {
|
||||
|
||||
+3
-1
@@ -80,7 +80,9 @@ public class SubscriptionCurrencyUtil {
|
||||
* BigDecimal)
|
||||
*/
|
||||
static BigDecimal convertGoogleMoneyToApiAmount(final Money money) {
|
||||
final BigDecimal fractionalComponent = BigDecimal.valueOf(money.getNanos()).scaleByPowerOfTen(-9);
|
||||
final BigDecimal fractionalComponent = money.getNanos() == null
|
||||
? BigDecimal.ZERO
|
||||
: BigDecimal.valueOf(money.getNanos()).scaleByPowerOfTen(-9);
|
||||
final BigDecimal amount = BigDecimal.valueOf(money.getUnits()).add(fractionalComponent);
|
||||
return convertConfiguredAmountToApiAmount(money.getCurrencyCode(), amount);
|
||||
}
|
||||
|
||||
+8
-1
@@ -68,7 +68,14 @@ public class VirtualThreadPinEventMonitor implements Managed {
|
||||
@Override
|
||||
public void stop() throws InterruptedException {
|
||||
// flushes events and waits for callbacks to finish
|
||||
recordingStream.stop();
|
||||
try {
|
||||
recordingStream.stop();
|
||||
} catch (final IllegalStateException _) {
|
||||
// The JFR recorder registers its own shutdown hook with the JVM.
|
||||
// Since shutdown hook execution order is not guaranteed but JFR's hook usually runs early,
|
||||
// this recording may already be stopped before our managed resource cleanup runs.
|
||||
logger.info("RecordingStream already stopped");
|
||||
}
|
||||
// immediately frees all resources
|
||||
recordingStream.close();
|
||||
}
|
||||
|
||||
+30
-11
@@ -5,24 +5,23 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.workers;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import io.dropwizard.core.Application;
|
||||
import io.dropwizard.core.setup.Environment;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.DistributionSummary;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Objects;
|
||||
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.backup.BackupManager;
|
||||
import reactor.core.scheduler.Schedulers;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Objects;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
public class BackupMetricsCommand extends AbstractCommandWithDependencies {
|
||||
|
||||
@@ -67,17 +66,37 @@ public class BackupMetricsCommand extends AbstractCommandWithDependencies {
|
||||
"timeSinceLastRefresh"));
|
||||
final DistributionSummary timeSinceLastMediaRefresh = Metrics.summary(name(getClass(),
|
||||
"timeSinceLastMediaRefresh"));
|
||||
final DistributionSummary numMediaObjects = Metrics.summary(name(getClass(),
|
||||
"numObjects"));
|
||||
final DistributionSummary mediaBytesUsed = Metrics.summary(name(getClass(),
|
||||
"bytesUsed"));
|
||||
|
||||
final Counter freeTierBackups = Metrics.counter(name(getClass(), "backups"), "tier", "free");
|
||||
final Counter paidTierBackups = Metrics.counter(name(getClass(), "backups"), "tier", "paid");
|
||||
|
||||
|
||||
final BackupManager backupManager = commandDependencies.backupManager();
|
||||
final Long backupsExpired = backupManager
|
||||
.listBackupAttributes(segments, Schedulers.parallel())
|
||||
final Long backupsCrawled = backupManager
|
||||
.listBackupAttributes(segments)
|
||||
.doOnNext(backupMetadata -> {
|
||||
timeSinceLastRefresh.record(timeSince(backupMetadata.lastRefresh()).getSeconds());
|
||||
timeSinceLastMediaRefresh.record(timeSince(backupMetadata.lastMediaRefresh()).getSeconds());
|
||||
|
||||
final boolean hasMediaTier = Duration
|
||||
.between(backupMetadata.lastMediaRefresh(), backupMetadata.lastRefresh())
|
||||
.abs()
|
||||
.compareTo(Duration.ofDays(1)) < 1;
|
||||
if (hasMediaTier) {
|
||||
numMediaObjects.record(backupMetadata.numObjects());
|
||||
mediaBytesUsed.record(backupMetadata.bytesUsed());
|
||||
paidTierBackups.increment();
|
||||
} else {
|
||||
freeTierBackups.increment();
|
||||
}
|
||||
})
|
||||
.count()
|
||||
.block();
|
||||
logger.info("Crawled {} backups", backupsExpired);
|
||||
logger.info("Crawled {} backups", backupsCrawled);
|
||||
}
|
||||
|
||||
private Duration timeSince(Instant t) {
|
||||
|
||||
+1
-1
@@ -74,7 +74,7 @@ public class BackupUsageRecalculationCommand extends AbstractCommandWithDependen
|
||||
|
||||
final BackupManager backupManager = commandDependencies.backupManager();
|
||||
final Long backupsConsidered = backupManager
|
||||
.listBackupAttributes(segments, Schedulers.parallel())
|
||||
.listBackupAttributes(segments)
|
||||
.flatMap(attrs -> Mono.fromCompletionStage(() -> backupManager.recalculateQuota(attrs)).doOnNext(maybeRecalculationResult -> maybeRecalculationResult.ifPresent(recalculationResult -> {
|
||||
if (!recalculationResult.newUsage().equals(recalculationResult.oldUsage())) {
|
||||
logger.info("Recalculated usage. oldUsage={}, newUsage={}, lastRefresh={}, lastMediaRefresh={}",
|
||||
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.workers;
|
||||
|
||||
import io.dropwizard.core.Application;
|
||||
import io.dropwizard.core.setup.Environment;
|
||||
import java.time.Clock;
|
||||
import java.util.Base64;
|
||||
import java.util.Optional;
|
||||
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.storage.IssuedReceiptsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.SubscriberCredentials;
|
||||
import org.whispersystems.textsecuregcm.storage.SubscriptionManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Subscriptions;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentProcessor;
|
||||
|
||||
public class ClearIssuedReceiptRedemptionsCommand extends AbstractCommandWithDependencies {
|
||||
|
||||
private final Logger logger = LoggerFactory.getLogger(ClearIssuedReceiptRedemptionsCommand.class);
|
||||
|
||||
public ClearIssuedReceiptRedemptionsCommand() {
|
||||
super(new Application<>() {
|
||||
@Override
|
||||
public void run(WhisperServerConfiguration configuration, Environment environment) {
|
||||
|
||||
}
|
||||
}, "clear-issued-receipt-redemptions", "Clear issued receipt redemptions");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void configure(Subparser subparser) {
|
||||
super.configure(subparser);
|
||||
subparser.addArgument("-s", "--subscriber-id")
|
||||
.dest("subscriberId")
|
||||
.type(String.class)
|
||||
.required(true)
|
||||
.help("The subscriber-id whose receipt redemptions should be clear");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void run(Environment environment, Namespace namespace, WhisperServerConfiguration configuration,
|
||||
CommandDependencies deps) throws Exception {
|
||||
try {
|
||||
final String subscriberId = namespace.getString("subscriberId");
|
||||
|
||||
final SubscriberCredentials creds = SubscriberCredentials
|
||||
.process(Optional.empty(), subscriberId, Clock.systemUTC());
|
||||
|
||||
final IssuedReceiptsManager issuedReceiptsManager = deps.issuedReceiptsManager();
|
||||
final SubscriptionManager subscriptionManager = deps.subscriptionManager();
|
||||
|
||||
final Subscriptions.Record subscriber = subscriptionManager.getSubscriber(creds);
|
||||
final PaymentProvider processorType = subscriber.getProcessorCustomer()
|
||||
.orElseThrow(() -> new IllegalArgumentException("susbcriber did not have a subscription"))
|
||||
.processor();
|
||||
final SubscriptionPaymentProcessor processor = switch (processorType) {
|
||||
case APPLE_APP_STORE -> deps.appleAppStoreManager();
|
||||
case GOOGLE_PLAY_BILLING -> deps.googlePlayBillingManager();
|
||||
default ->
|
||||
throw new IllegalStateException("Cannot clear issued receipts for a non-IAP processor: " + processorType);
|
||||
};
|
||||
final SubscriptionPaymentProcessor.ReceiptItem receiptItem = processor.getReceiptItem(subscriber.subscriptionId);
|
||||
final boolean deleted = issuedReceiptsManager.clearIssuance(receiptItem.itemId(), processorType).join();
|
||||
logger.info("Deleted issuances for receiptItem: {}, subscriberId: {}, hadExistingIssuances: {}",
|
||||
receiptItem.itemId(), subscriberId, deleted);
|
||||
} catch (Exception ex) {
|
||||
logger.warn("Removal Exception", ex);
|
||||
throw new RuntimeException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
final String subscriberId = "7ywqmymkSMBkBi9v06Iy4AN8DiN_lg8gHXM8TSpO0Z0";
|
||||
|
||||
final SubscriberCredentials creds = SubscriberCredentials
|
||||
.process(Optional.empty(), subscriberId, Clock.systemUTC());
|
||||
System.out.println(Base64.getEncoder().encodeToString(creds.subscriberUser()));
|
||||
|
||||
final String pc = "AWN1c19TV3hDUEhlWDBldzB0UA==";
|
||||
final byte[] bc = Base64.getDecoder().decode(pc);
|
||||
System.out.println(bc[0]);
|
||||
System.out.println(new String(bc, 1, bc.length - 1));
|
||||
}
|
||||
}
|
||||
+47
-2
@@ -11,16 +11,23 @@ import com.codahale.metrics.MetricRegistry;
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import io.dropwizard.core.setup.Environment;
|
||||
import io.lettuce.core.resource.ClientResources;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.GeneralSecurityException;
|
||||
import java.security.InvalidKeyException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.cert.CertificateException;
|
||||
import java.time.Clock;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.SynchronousQueue;
|
||||
import org.signal.libsignal.zkgroup.GenericServerSecretParams;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.ServerSecretParams;
|
||||
import org.signal.libsignal.zkgroup.receipts.ServerZkReceiptOperations;
|
||||
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.WhisperServerService;
|
||||
import org.whispersystems.textsecuregcm.attachments.TusAttachmentGenerator;
|
||||
@@ -38,6 +45,7 @@ import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.experiment.PushNotificationExperimentSamples;
|
||||
import org.whispersystems.textsecuregcm.grpc.net.GrpcClientConnectionManager;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.metrics.MicrometerAwsSdkMetricPublisher;
|
||||
import org.whispersystems.textsecuregcm.push.APNSender;
|
||||
import org.whispersystems.textsecuregcm.push.FcmSender;
|
||||
@@ -72,6 +80,10 @@ import org.whispersystems.textsecuregcm.storage.ReportMessageDynamoDb;
|
||||
import org.whispersystems.textsecuregcm.storage.ReportMessageManager;
|
||||
import org.whispersystems.textsecuregcm.storage.SingleUseECPreKeyStore;
|
||||
import org.whispersystems.textsecuregcm.storage.SingleUseKEMPreKeyStore;
|
||||
import org.whispersystems.textsecuregcm.storage.SubscriptionManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Subscriptions;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.AppleAppStoreManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.GooglePlayBillingManager;
|
||||
import org.whispersystems.textsecuregcm.util.ManagedAwsCrt;
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
import reactor.core.scheduler.Schedulers;
|
||||
@@ -101,6 +113,9 @@ record CommandDependencies(
|
||||
ClientResources.Builder redisClusterClientResourcesBuilder,
|
||||
BackupManager backupManager,
|
||||
IssuedReceiptsManager issuedReceiptsManager,
|
||||
GooglePlayBillingManager googlePlayBillingManager,
|
||||
AppleAppStoreManager appleAppStoreManager,
|
||||
SubscriptionManager subscriptionManager,
|
||||
DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
|
||||
DynamoDbAsyncClient dynamoDbAsyncClient,
|
||||
PhoneNumberIdentifiers phoneNumberIdentifiers,
|
||||
@@ -110,9 +125,11 @@ record CommandDependencies(
|
||||
final String name,
|
||||
final Environment environment,
|
||||
final WhisperServerConfiguration configuration)
|
||||
throws IOException, CertificateException, NoSuchAlgorithmException, InvalidKeyException {
|
||||
throws IOException, GeneralSecurityException, InvalidInputException {
|
||||
Clock clock = Clock.systemUTC();
|
||||
|
||||
MetricsUtil.configureLogging(configuration, environment);
|
||||
|
||||
environment.getObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
|
||||
|
||||
final AwsCredentialsProvider awsCredentialsProvider = configuration.getAwsCredentialsConfiguration().build();
|
||||
@@ -300,7 +317,8 @@ record CommandDependencies(
|
||||
configuration.getCdn3StorageManagerConfiguration()),
|
||||
secureValueRecoveryBCredentialsGenerator,
|
||||
secureValueRecoveryBClient,
|
||||
clock);
|
||||
clock,
|
||||
dynamicConfigurationManager);
|
||||
|
||||
final IssuedReceiptsManager issuedReceiptsManager = new IssuedReceiptsManager(
|
||||
configuration.getDynamoDbTables().getIssuedReceipts().getTableName(),
|
||||
@@ -309,6 +327,30 @@ record CommandDependencies(
|
||||
configuration.getDynamoDbTables().getIssuedReceipts().getGenerator(),
|
||||
configuration.getDynamoDbTables().getIssuedReceipts().getmaxIssuedReceiptsPerPaymentId());
|
||||
|
||||
final ServerSecretParams zkSecretParams = new ServerSecretParams(configuration.getZkConfig().serverSecret().value());
|
||||
final ServerZkReceiptOperations zkReceiptOperations = new ServerZkReceiptOperations(zkSecretParams);
|
||||
GooglePlayBillingManager googlePlayBillingManager = new GooglePlayBillingManager(
|
||||
new ByteArrayInputStream(configuration.getGooglePlayBilling().credentialsJson().value().getBytes(StandardCharsets.UTF_8)),
|
||||
configuration.getGooglePlayBilling().packageName(),
|
||||
configuration.getGooglePlayBilling().applicationName(),
|
||||
configuration.getGooglePlayBilling().productIdToLevel());
|
||||
AppleAppStoreManager appleAppStoreManager = new AppleAppStoreManager(
|
||||
configuration.getAppleAppStore().env(),
|
||||
configuration.getAppleAppStore().bundleId(),
|
||||
configuration.getAppleAppStore().appAppleId(),
|
||||
configuration.getAppleAppStore().issuerId(),
|
||||
configuration.getAppleAppStore().keyId(),
|
||||
configuration.getAppleAppStore().encodedKey().value(),
|
||||
configuration.getAppleAppStore().subscriptionGroupId(),
|
||||
configuration.getAppleAppStore().productIdToLevel(),
|
||||
configuration.getAppleAppStore().appleRootCerts(),
|
||||
configuration.getAppleAppStore().retryConfigurationName());
|
||||
final SubscriptionManager subscriptionManager = new SubscriptionManager(
|
||||
new Subscriptions(configuration.getDynamoDbTables().getSubscriptions().getTableName(), dynamoDbAsyncClient),
|
||||
List.of(googlePlayBillingManager, appleAppStoreManager),
|
||||
zkReceiptOperations,
|
||||
issuedReceiptsManager);
|
||||
|
||||
APNSender apnSender = new APNSender(apnSenderExecutor, configuration.getApnConfiguration());
|
||||
FcmSender fcmSender = new FcmSender(fcmSenderExecutor, configuration.getFcmConfiguration().credentials().value());
|
||||
PushNotificationScheduler pushNotificationScheduler = new PushNotificationScheduler(pushSchedulerCluster,
|
||||
@@ -345,6 +387,9 @@ record CommandDependencies(
|
||||
redisClientResourcesBuilder,
|
||||
backupManager,
|
||||
issuedReceiptsManager,
|
||||
googlePlayBillingManager,
|
||||
appleAppStoreManager,
|
||||
subscriptionManager,
|
||||
dynamicConfigurationManager,
|
||||
dynamoDbAsyncClient,
|
||||
phoneNumberIdentifiers,
|
||||
|
||||
-3
@@ -14,7 +14,6 @@ import java.time.Duration;
|
||||
import net.sourceforge.argparse4j.inf.Namespace;
|
||||
import net.sourceforge.argparse4j.inf.Subparser;
|
||||
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagePersister;
|
||||
import org.whispersystems.textsecuregcm.util.logging.UncaughtExceptionHandler;
|
||||
@@ -70,8 +69,6 @@ public class MessagePersisterServiceCommand extends ServerCommand<WhisperServerC
|
||||
|
||||
environment.lifecycle().manage(messagePersister);
|
||||
|
||||
MetricsUtil.registerSystemResourceMetrics(environment);
|
||||
|
||||
super.run(environment, namespace, configuration);
|
||||
}
|
||||
|
||||
|
||||
-2
@@ -166,8 +166,6 @@ public class ProcessScheduledJobsServiceCommand extends ServerCommand<WhisperSer
|
||||
|
||||
environment.lifecycle().manage(new ScheduledJobProcessor(jobScheduler, scheduledExecutorService, fixedDelaySeconds));
|
||||
|
||||
MetricsUtil.registerSystemResourceMetrics(environment);
|
||||
|
||||
super.run(environment, namespace, configuration);
|
||||
}
|
||||
}
|
||||
-2
@@ -96,8 +96,6 @@ public class ScheduledApnPushNotificationSenderServiceCommand extends ServerComm
|
||||
|
||||
environment.lifecycle().manage(pushNotificationScheduler);
|
||||
|
||||
MetricsUtil.registerSystemResourceMetrics(environment);
|
||||
|
||||
super.run(environment, namespace, configuration);
|
||||
}
|
||||
|
||||
|
||||
+1
@@ -1 +1,2 @@
|
||||
org.whispersystems.textsecuregcm.metrics.LogstashTcpSocketAppenderFactory
|
||||
org.whispersystems.textsecuregcm.metrics.OpenTelemetryAppenderFactory
|
||||
+23
-23
@@ -88,88 +88,88 @@ class OptionalAccessTest {
|
||||
when(inactiveTargetAccount.isIdentifiedBy(inactiveTargetAccountAciIdentifier)).thenReturn(true);
|
||||
|
||||
return List.of(
|
||||
// Unidentified caller; correct UAK
|
||||
Arguments.of(Optional.empty(),
|
||||
Arguments.argumentSet("Unidentified caller; correct UAK",
|
||||
Optional.empty(),
|
||||
Optional.of(correctUakHeader),
|
||||
Optional.of(targetAccount),
|
||||
targetAccountAciIdentifier,
|
||||
OptionalAccess.ALL_DEVICES_SELECTOR,
|
||||
OptionalInt.empty()),
|
||||
|
||||
// Identified caller; no UAK needed
|
||||
Arguments.of(Optional.of(mock(Account.class)),
|
||||
Arguments.argumentSet("Identified caller; no UAK needed",
|
||||
Optional.of(mock(Account.class)),
|
||||
Optional.empty(),
|
||||
Optional.of(targetAccount),
|
||||
targetAccountAciIdentifier,
|
||||
OptionalAccess.ALL_DEVICES_SELECTOR,
|
||||
OptionalInt.empty()),
|
||||
|
||||
// Unidentified caller; target account not found
|
||||
Arguments.of(Optional.empty(),
|
||||
Arguments.argumentSet("Unidentified caller; target account not found",
|
||||
Optional.empty(),
|
||||
Optional.empty(),
|
||||
Optional.empty(),
|
||||
new AciServiceIdentifier(UUID.randomUUID()),
|
||||
OptionalAccess.ALL_DEVICES_SELECTOR,
|
||||
OptionalInt.of(401)),
|
||||
|
||||
// Identified caller; target account not found
|
||||
Arguments.of(Optional.of(mock(Account.class)),
|
||||
Arguments.argumentSet("Identified caller; target account not found",
|
||||
Optional.of(mock(Account.class)),
|
||||
Optional.empty(),
|
||||
Optional.empty(),
|
||||
new AciServiceIdentifier(UUID.randomUUID()),
|
||||
OptionalAccess.ALL_DEVICES_SELECTOR,
|
||||
OptionalInt.of(404)),
|
||||
|
||||
// Unidentified caller; target account found, but target device not found
|
||||
Arguments.of(Optional.empty(),
|
||||
Arguments.argumentSet("Unidentified caller; target account found, but target device not found",
|
||||
Optional.empty(),
|
||||
Optional.of(correctUakHeader),
|
||||
Optional.of(targetAccount),
|
||||
targetAccountAciIdentifier,
|
||||
String.valueOf(Device.PRIMARY_ID + 1),
|
||||
OptionalInt.of(401)),
|
||||
|
||||
// Unidentified caller; target account found, but incorrect UAK provided
|
||||
Arguments.of(Optional.empty(),
|
||||
Arguments.argumentSet("Unidentified caller; target account found, but incorrect UAK provided",
|
||||
Optional.empty(),
|
||||
Optional.of(incorrectUakHeader),
|
||||
Optional.of(targetAccount),
|
||||
targetAccountAciIdentifier,
|
||||
OptionalAccess.ALL_DEVICES_SELECTOR,
|
||||
OptionalInt.of(401)),
|
||||
|
||||
// Unidentified caller; target account found, but has no UAK
|
||||
Arguments.of(Optional.empty(),
|
||||
Arguments.argumentSet("Unidentified caller; target account found, but has no UAK",
|
||||
Optional.empty(),
|
||||
Optional.of(correctUakHeader),
|
||||
Optional.of(noUakTargetAccount),
|
||||
noUakTargetAccountAciIdentifier,
|
||||
OptionalAccess.ALL_DEVICES_SELECTOR,
|
||||
OptionalInt.of(401)),
|
||||
|
||||
// Unidentified caller; target account found, allows unrestricted unidentified access, so PNI target doesn't matter
|
||||
Arguments.of(Optional.empty(),
|
||||
Arguments.argumentSet("Unidentified caller; target account found, PNI target has priority over allows-unrestricted-unidentified-access",
|
||||
Optional.empty(),
|
||||
Optional.of(incorrectUakHeader),
|
||||
Optional.of(allowAllTargetAccount),
|
||||
allowAllTargetAccountPniIdentifier,
|
||||
OptionalAccess.ALL_DEVICES_SELECTOR,
|
||||
OptionalInt.empty()),
|
||||
OptionalInt.of(401)),
|
||||
|
||||
// Unidentified caller; target account found, but inactive
|
||||
Arguments.of(Optional.empty(),
|
||||
Arguments.argumentSet("Unidentified caller; target account found, but inactive",
|
||||
Optional.empty(),
|
||||
Optional.of(correctUakHeader),
|
||||
Optional.of(inactiveTargetAccount),
|
||||
inactiveTargetAccountAciIdentifier,
|
||||
OptionalAccess.ALL_DEVICES_SELECTOR,
|
||||
OptionalInt.empty()),
|
||||
|
||||
// Malformed device ID
|
||||
Arguments.of(Optional.empty(),
|
||||
Arguments.argumentSet("Malformed device ID",
|
||||
Optional.empty(),
|
||||
Optional.of(correctUakHeader),
|
||||
Optional.of(targetAccount),
|
||||
targetAccountAciIdentifier,
|
||||
"not a valid identifier",
|
||||
OptionalInt.of(422)),
|
||||
|
||||
// Unidentified caller; target account found, but PNI identifier
|
||||
Arguments.of(Optional.empty(),
|
||||
Arguments.argumentSet("Unidentified caller; target account found, but PNI identifier",
|
||||
Optional.empty(),
|
||||
Optional.of(correctUakHeader),
|
||||
Optional.of(targetAccount),
|
||||
targetAccountPniIdentifier,
|
||||
|
||||
+26
@@ -9,6 +9,7 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyInt;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
@@ -57,6 +58,7 @@ import org.signal.libsignal.zkgroup.receipts.ServerZkReceiptOperations;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiterConfig;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
@@ -511,6 +513,26 @@ public class BackupAuthManagerTest {
|
||||
return clientOps.createReceiptCredentialPresentation(receiptCredential);
|
||||
}
|
||||
|
||||
@CartesianTest
|
||||
void testCheckLimits(
|
||||
@CartesianTest.Values(booleans = {true, false}) boolean messageLimited,
|
||||
@CartesianTest.Values(booleans = {true, false}) boolean mediaLimited,
|
||||
@CartesianTest.Values(booleans = {true, false}) boolean hasVoucher) {
|
||||
clock.pin(Instant.EPOCH);
|
||||
final BackupAuthManager authManager = create(BackupLevel.FREE, rateLimiter(aci, messageLimited, mediaLimited));
|
||||
final Account account = new MockAccountBuilder()
|
||||
.backupVoucher(hasVoucher
|
||||
? new Account.BackupVoucher(1, Instant.EPOCH.plus(Duration.ofSeconds(1)))
|
||||
: null)
|
||||
.build();
|
||||
final BackupAuthManager.BackupIdRotationLimit limit = authManager.checkBackupIdRotationLimit(account)
|
||||
.toCompletableFuture().join();
|
||||
final boolean expectHasPermits = !messageLimited && (!mediaLimited || !hasVoucher);
|
||||
final Duration expectedDuration = expectHasPermits ? Duration.ZERO : Duration.ofDays(1);
|
||||
assertThat(limit.hasPermitsRemaining()).isEqualTo(expectHasPermits);
|
||||
assertThat(limit.nextPermitAvailable()).isEqualTo(expectedDuration);
|
||||
}
|
||||
|
||||
|
||||
@CartesianTest
|
||||
void testChangeIdRateLimits(
|
||||
@@ -643,11 +665,15 @@ public class BackupAuthManagerTest {
|
||||
final RateLimiters limiters = mock(RateLimiters.class);
|
||||
|
||||
final RateLimiter allowLimiter = mock(RateLimiter.class);
|
||||
when(allowLimiter.hasAvailablePermitsAsync(eq(aci), anyInt())).thenReturn(CompletableFuture.completedFuture(true));
|
||||
when(allowLimiter.validateAsync(aci)).thenReturn(CompletableFuture.completedFuture(null));
|
||||
when(allowLimiter.config()).thenReturn(new RateLimiterConfig(1, Duration.ofDays(1), false));
|
||||
|
||||
final RateLimiter denyLimiter = mock(RateLimiter.class);
|
||||
when(denyLimiter.hasAvailablePermitsAsync(eq(aci), anyInt())).thenReturn(CompletableFuture.completedFuture(false));
|
||||
when(denyLimiter.validateAsync(aci))
|
||||
.thenReturn(CompletableFuture.failedFuture(new RateLimitExceededException(null)));
|
||||
when(denyLimiter.config()).thenReturn(new RateLimiterConfig(1, Duration.ofDays(1), false));
|
||||
|
||||
when(limiters.forDescriptor(RateLimiters.For.SET_BACKUP_ID))
|
||||
.thenReturn(rateLimitBackupId ? denyLimiter : allowLimiter);
|
||||
|
||||
+48
-39
@@ -22,6 +22,7 @@ import static org.mockito.Mockito.verifyNoMoreInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.whispersystems.textsecuregcm.util.MockUtils.randomSecretBytes;
|
||||
|
||||
import io.dropwizard.util.DataSize;
|
||||
import io.grpc.Status;
|
||||
import io.grpc.StatusRuntimeException;
|
||||
import java.io.IOException;
|
||||
@@ -73,10 +74,13 @@ import org.whispersystems.textsecuregcm.auth.AuthenticatedBackupUser;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
|
||||
import org.whispersystems.textsecuregcm.configuration.SecureValueRecoveryConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicBackupConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecoveryClient;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamoDbExtension;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamoDbExtensionSchema;
|
||||
import org.whispersystems.textsecuregcm.util.AttributeValues;
|
||||
@@ -100,6 +104,7 @@ public class BackupManagerTest {
|
||||
private static final CopyParameters COPY_PARAM = new CopyParameters(
|
||||
3, "abc", 100,
|
||||
COPY_ENCRYPTION_PARAM, TestRandomUtil.nextBytes(15));
|
||||
private static final long MAX_TOTAL_MEDIA_BYTES = DataSize.mebibytes(1).toBytes();
|
||||
|
||||
private final TestClock testClock = TestClock.now();
|
||||
private final BackupAuthTestUtil backupAuthTestUtil = new BackupAuthTestUtil(testClock);
|
||||
@@ -109,6 +114,8 @@ public class BackupManagerTest {
|
||||
private final RemoteStorageManager remoteStorageManager = mock(RemoteStorageManager.class);
|
||||
private final byte[] backupKey = TestRandomUtil.nextBytes(32);
|
||||
private final UUID aci = UUID.randomUUID();
|
||||
private final DynamicBackupConfiguration backupConfiguration = new DynamicBackupConfiguration(
|
||||
3, 4, 5, Duration.ofSeconds(30), MAX_TOTAL_MEDIA_BYTES);
|
||||
|
||||
|
||||
private static final SecureValueRecoveryConfiguration CFG = new SecureValueRecoveryConfiguration(
|
||||
@@ -139,6 +146,12 @@ public class BackupManagerTest {
|
||||
DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(),
|
||||
DynamoDbExtensionSchema.Tables.BACKUPS.tableName(),
|
||||
testClock);
|
||||
@SuppressWarnings("unchecked") final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager =
|
||||
mock(DynamicConfigurationManager.class);
|
||||
final DynamicConfiguration dynamicConfiguration = mock(DynamicConfiguration.class);
|
||||
when(dynamicConfiguration.getBackupConfiguration()).thenReturn(backupConfiguration);
|
||||
when(dynamicConfigurationManager.getConfiguration()).thenReturn(dynamicConfiguration);
|
||||
|
||||
this.backupManager = new BackupManager(
|
||||
backupsDb,
|
||||
backupAuthTestUtil.params,
|
||||
@@ -148,7 +161,8 @@ public class BackupManagerTest {
|
||||
remoteStorageManager,
|
||||
svrbCredentialGenerator,
|
||||
svrbClient,
|
||||
testClock);
|
||||
testClock,
|
||||
dynamicConfigurationManager);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@@ -490,7 +504,7 @@ public class BackupManagerTest {
|
||||
.map(source -> new CopyParameters(3, source, 100, COPY_ENCRYPTION_PARAM, TestRandomUtil.nextBytes(15)))
|
||||
.toList();
|
||||
|
||||
final int slowIndex = BackupManager.USAGE_CHECKPOINT_COUNT - 1;
|
||||
final int slowIndex = backupConfiguration.usageCheckpointCount() - 1;
|
||||
final CompletableFuture<Void> slow = new CompletableFuture<>();
|
||||
when(remoteStorageManager.copy(eq(3), anyString(), eq(100), any(), anyString()))
|
||||
.thenReturn(CompletableFuture.completedFuture(null));
|
||||
@@ -507,15 +521,14 @@ public class BackupManagerTest {
|
||||
|
||||
// Copying can start on the next batch of USAGE_CHECKPOINT_COUNT before the current one is done, so we should see
|
||||
// at least one usage update, and at most 2
|
||||
final UsageInfo usage = backupsDb.getMediaUsage(backupUser).join().usageInfo();
|
||||
final long bytesPerObject = COPY_ENCRYPTION_PARAM.outputSize(100);
|
||||
assertThat(backupsDb.getMediaUsage(backupUser).join().usageInfo()).isIn(
|
||||
new UsageInfo(
|
||||
bytesPerObject * BackupManager.USAGE_CHECKPOINT_COUNT,
|
||||
BackupManager.USAGE_CHECKPOINT_COUNT),
|
||||
bytesPerObject * backupConfiguration.usageCheckpointCount(),
|
||||
backupConfiguration.usageCheckpointCount()),
|
||||
new UsageInfo(
|
||||
2 * bytesPerObject * BackupManager.USAGE_CHECKPOINT_COUNT,
|
||||
2 * BackupManager.USAGE_CHECKPOINT_COUNT));
|
||||
2 * bytesPerObject * backupConfiguration.usageCheckpointCount(),
|
||||
2L * backupConfiguration.usageCheckpointCount()));
|
||||
|
||||
// We should still be waiting since we have a slow delete
|
||||
assertThat(future).isNotDone();
|
||||
@@ -558,6 +571,7 @@ public class BackupManagerTest {
|
||||
final List<CopyResult> results = backupManager.copyToBackup(backupUser, toCopy)
|
||||
.collectList().block();
|
||||
|
||||
assertThat(results).hasSize(3);
|
||||
assertThat(results.get(0).outcome()).isEqualTo(CopyResult.Outcome.SUCCESS);
|
||||
assertThat(results.get(1).outcome()).isEqualTo(CopyResult.Outcome.SOURCE_NOT_FOUND);
|
||||
assertThat(results.get(2).outcome()).isEqualTo(CopyResult.Outcome.SOURCE_WRONG_LENGTH);
|
||||
@@ -565,7 +579,7 @@ public class BackupManagerTest {
|
||||
// usage should be rolled back after a known copy failure
|
||||
final Map<String, AttributeValue> backup = getBackupItem(backupUser);
|
||||
assertThat(AttributeValues.getLong(backup, BackupsDb.ATTR_MEDIA_BYTES_USED, -1L))
|
||||
.isEqualTo(toCopy.get(0).destinationObjectSize());
|
||||
.isEqualTo(toCopy.getFirst().destinationObjectSize());
|
||||
assertThat(AttributeValues.getLong(backup, BackupsDb.ATTR_MEDIA_COUNT, -1L)).isEqualTo(1L);
|
||||
}
|
||||
|
||||
@@ -587,10 +601,10 @@ public class BackupManagerTest {
|
||||
|
||||
// set the backupsDb to be out of quota at t=0
|
||||
testClock.pin(Instant.ofEpochSecond(1));
|
||||
backupsDb.setMediaUsage(backupUser, new UsageInfo(BackupManager.MAX_TOTAL_BACKUP_MEDIA_BYTES, 1000)).join();
|
||||
backupsDb.setMediaUsage(backupUser, new UsageInfo(MAX_TOTAL_MEDIA_BYTES, 1000)).join();
|
||||
// check still within staleness bound (t=0 + 1 day - 1 sec)
|
||||
testClock.pin(Instant.ofEpochSecond(0)
|
||||
.plus(BackupManager.MAX_QUOTA_STALENESS)
|
||||
.plus(backupConfiguration.maxQuotaStaleness())
|
||||
.minus(Duration.ofSeconds(1)));
|
||||
|
||||
// Try to copy
|
||||
@@ -602,7 +616,7 @@ public class BackupManagerTest {
|
||||
final AuthenticatedBackupUser backupUser = backupUser(TestRandomUtil.nextBytes(16), BackupCredentialType.MEDIA, BackupLevel.PAID);
|
||||
final String backupMediaPrefix = "%s/%s/".formatted(backupUser.backupDir(), backupUser.mediaDir());
|
||||
|
||||
final long remainingAfterRecalc = BackupManager.MAX_TOTAL_BACKUP_MEDIA_BYTES - COPY_PARAM.destinationObjectSize();
|
||||
final long remainingAfterRecalc = MAX_TOTAL_MEDIA_BYTES - COPY_PARAM.destinationObjectSize();
|
||||
|
||||
// on recalculation, say there's actually enough left to do the copy
|
||||
when(remoteStorageManager.calculateBytesUsed(eq(backupMediaPrefix)))
|
||||
@@ -610,8 +624,8 @@ public class BackupManagerTest {
|
||||
|
||||
// set the backupsDb to be totally out of quota at t=0
|
||||
testClock.pin(Instant.ofEpochSecond(0));
|
||||
backupsDb.setMediaUsage(backupUser, new UsageInfo(BackupManager.MAX_TOTAL_BACKUP_MEDIA_BYTES, 1000)).join();
|
||||
testClock.pin(Instant.ofEpochSecond(0).plus(BackupManager.MAX_QUOTA_STALENESS));
|
||||
backupsDb.setMediaUsage(backupUser, new UsageInfo(MAX_TOTAL_MEDIA_BYTES, 1000)).join();
|
||||
testClock.pin(Instant.ofEpochSecond(0).plus(backupConfiguration.maxQuotaStaleness()));
|
||||
|
||||
// Should recalculate quota and copy can succeed
|
||||
assertThat(copy(backupUser).outcome()).isEqualTo(CopyResult.Outcome.SUCCESS);
|
||||
@@ -619,8 +633,8 @@ public class BackupManagerTest {
|
||||
// backupsDb should have the new value
|
||||
final BackupsDb.TimestampedUsageInfo info = backupsDb.getMediaUsage(backupUser).join();
|
||||
assertThat(info.lastRecalculationTime())
|
||||
.isEqualTo(Instant.ofEpochSecond(0).plus(BackupManager.MAX_QUOTA_STALENESS));
|
||||
assertThat(info.usageInfo().bytesUsed()).isEqualTo(BackupManager.MAX_TOTAL_BACKUP_MEDIA_BYTES);
|
||||
.isEqualTo(Instant.ofEpochSecond(0).plus(backupConfiguration.maxQuotaStaleness()));
|
||||
assertThat(info.usageInfo().bytesUsed()).isEqualTo(MAX_TOTAL_MEDIA_BYTES);
|
||||
assertThat(info.usageInfo().numObjects()).isEqualTo(1001);
|
||||
}
|
||||
|
||||
@@ -634,16 +648,16 @@ public class BackupManagerTest {
|
||||
|
||||
final long destSize = COPY_PARAM.destinationObjectSize();
|
||||
final long originalRemainingSpace =
|
||||
BackupManager.MAX_TOTAL_BACKUP_MEDIA_BYTES - (hasSpaceBeforeRecalc ? destSize : (destSize - 1));
|
||||
MAX_TOTAL_MEDIA_BYTES - (hasSpaceBeforeRecalc ? destSize : (destSize - 1));
|
||||
final long afterRecalcRemainingSpace =
|
||||
BackupManager.MAX_TOTAL_BACKUP_MEDIA_BYTES - (hasSpaceAfterRecalc ? destSize : (destSize - 1));
|
||||
MAX_TOTAL_MEDIA_BYTES - (hasSpaceAfterRecalc ? destSize : (destSize - 1));
|
||||
|
||||
// set the backupsDb to be out of quota at t=0
|
||||
testClock.pin(Instant.ofEpochSecond(0));
|
||||
backupsDb.setMediaUsage(backupUser, new UsageInfo(originalRemainingSpace, 1000)).join();
|
||||
|
||||
if (doesReaclc) {
|
||||
testClock.pin(Instant.ofEpochSecond(0).plus(BackupManager.MAX_QUOTA_STALENESS).plus(Duration.ofSeconds(1)));
|
||||
testClock.pin(Instant.ofEpochSecond(0).plus(backupConfiguration.maxQuotaStaleness()).plus(Duration.ofSeconds(1)));
|
||||
when(remoteStorageManager.calculateBytesUsed(eq(backupMediaPrefix)))
|
||||
.thenReturn(CompletableFuture.completedFuture(new UsageInfo(afterRecalcRemainingSpace, 1000)));
|
||||
}
|
||||
@@ -670,7 +684,9 @@ public class BackupManagerTest {
|
||||
backupsDb.setMediaUsage(backupUser, oldUsage).join();
|
||||
when(remoteStorageManager.calculateBytesUsed(eq(backupMediaPrefix)))
|
||||
.thenReturn(CompletableFuture.completedFuture(newUsage));
|
||||
final StoredBackupAttributes attrs = backupManager.listBackupAttributes(1, Schedulers.immediate()).single().block();
|
||||
final StoredBackupAttributes attrs = backupManager.listBackupAttributes(1)
|
||||
.single()
|
||||
.blockOptional().orElseThrow();
|
||||
|
||||
testClock.pin(Instant.ofEpochSecond(456));
|
||||
assertThat(backupManager.recalculateQuota(attrs).toCompletableFuture().join())
|
||||
@@ -738,7 +754,8 @@ public class BackupManagerTest {
|
||||
// The original prefix to expire should be flagged as requiring expiration
|
||||
final ExpiredBackup expiredBackup = backupManager
|
||||
.getExpiredBackups(1, Schedulers.immediate(), Instant.ofEpochSecond(1L))
|
||||
.collectList().block()
|
||||
.collectList()
|
||||
.blockOptional().orElseThrow()
|
||||
.getFirst();
|
||||
assertThat(expiredBackup.hashedBackupId()).isEqualTo(hashedBackupId(original.backupId()));
|
||||
assertThat(expiredBackup.prefixToDelete()).isEqualTo(original.backupDir());
|
||||
@@ -770,11 +787,6 @@ public class BackupManagerTest {
|
||||
public void deleteWrongCredentialType() {
|
||||
final AuthenticatedBackupUser backupUser = backupUser(TestRandomUtil.nextBytes(16), BackupCredentialType.MESSAGES, BackupLevel.PAID);
|
||||
final byte[] mediaId = TestRandomUtil.nextBytes(16);
|
||||
final String backupMediaKey = "%s/%s/%s".formatted(
|
||||
backupUser.backupDir(),
|
||||
backupUser.mediaDir(),
|
||||
BackupManager.encodeMediaIdForCdn(mediaId));
|
||||
|
||||
assertThatThrownBy(() ->
|
||||
backupManager.deleteMedia(backupUser, List.of(new BackupManager.StorageDescriptor(5, mediaId))).then().block())
|
||||
.isInstanceOf(StatusRuntimeException.class)
|
||||
@@ -798,7 +810,7 @@ public class BackupManagerTest {
|
||||
BackupLevel.PAID);
|
||||
|
||||
// 100 objects, each 2 bytes large
|
||||
final List<byte[]> mediaIds = IntStream.range(0, 100).mapToObj(ig -> TestRandomUtil.nextBytes(16)).toList();
|
||||
final List<byte[]> mediaIds = IntStream.range(0, 100).mapToObj(_ -> TestRandomUtil.nextBytes(16)).toList();
|
||||
backupsDb.setMediaUsage(backupUser, new UsageInfo(200, 100)).join();
|
||||
|
||||
// One object is slow to delete
|
||||
@@ -806,7 +818,7 @@ public class BackupManagerTest {
|
||||
final String slowMediaKey = "%s/%s/%s".formatted(
|
||||
backupUser.backupDir(),
|
||||
backupUser.mediaDir(),
|
||||
BackupManager.encodeMediaIdForCdn(mediaIds.get(BackupManager.USAGE_CHECKPOINT_COUNT + 3)));
|
||||
BackupManager.encodeMediaIdForCdn(mediaIds.get(backupConfiguration.usageCheckpointCount() + 3)));
|
||||
|
||||
when(remoteStorageManager.delete(anyString())).thenReturn(CompletableFuture.completedFuture(2L));
|
||||
when(remoteStorageManager.delete(slowMediaKey)).thenReturn(slowFuture);
|
||||
@@ -819,21 +831,17 @@ public class BackupManagerTest {
|
||||
.toList());
|
||||
final ArrayBlockingQueue<BackupManager.StorageDescriptor> sds = new ArrayBlockingQueue<>(100);
|
||||
final CompletableFuture<Void> future = flux.doOnNext(sds::add).then().toFuture();
|
||||
for (int i = 0; i < BackupManager.USAGE_CHECKPOINT_COUNT; i++) {
|
||||
for (int i = 0; i < backupConfiguration.usageCheckpointCount(); i++) {
|
||||
sds.poll(1, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
assertThat(backupsDb.getMediaUsage(backupUser).join().usageInfo())
|
||||
.isEqualTo(new UsageInfo(
|
||||
200 - (2 * BackupManager.USAGE_CHECKPOINT_COUNT),
|
||||
100 - BackupManager.USAGE_CHECKPOINT_COUNT));
|
||||
// We should still be waiting since we have a slow delete
|
||||
assertThat(future).isNotDone();
|
||||
// But we should checkpoint the usage periodically
|
||||
assertThat(backupsDb.getMediaUsage(backupUser).join().usageInfo())
|
||||
.isEqualTo(new UsageInfo(
|
||||
200 - (2 * BackupManager.USAGE_CHECKPOINT_COUNT),
|
||||
100 - BackupManager.USAGE_CHECKPOINT_COUNT));
|
||||
200 - (2L * backupConfiguration.usageCheckpointCount()),
|
||||
100 - backupConfiguration.usageCheckpointCount()));
|
||||
|
||||
slowFuture.complete(2L);
|
||||
future.join();
|
||||
@@ -860,7 +868,7 @@ public class BackupManagerTest {
|
||||
// fail deletion 3, otherwise return the corresponding object's size as i
|
||||
final CompletableFuture<Long> deleteResult = i == 3
|
||||
? CompletableFuture.failedFuture(new IOException("oh no"))
|
||||
: CompletableFuture.completedFuture(Long.valueOf(i));
|
||||
: CompletableFuture.completedFuture((long) i);
|
||||
|
||||
when(remoteStorageManager.delete(backupMediaKey)).thenReturn(deleteResult);
|
||||
}
|
||||
@@ -870,7 +878,8 @@ public class BackupManagerTest {
|
||||
final List<BackupManager.StorageDescriptor> deleted = backupManager
|
||||
.deleteMedia(backupUser, descriptors)
|
||||
.onErrorComplete()
|
||||
.collectList().block();
|
||||
.collectList()
|
||||
.blockOptional().orElseThrow();
|
||||
// first two objects should be deleted
|
||||
assertThat(deleted.size()).isEqualTo(2);
|
||||
assertThat(backupsDb.getMediaUsage(backupUser).join().usageInfo())
|
||||
@@ -901,7 +910,7 @@ public class BackupManagerTest {
|
||||
@Test
|
||||
public void listExpiredBackups() {
|
||||
final List<AuthenticatedBackupUser> backupUsers = IntStream.range(0, 10)
|
||||
.mapToObj(i -> backupUser(TestRandomUtil.nextBytes(16), BackupCredentialType.MESSAGES, BackupLevel.PAID))
|
||||
.mapToObj(_ -> backupUser(TestRandomUtil.nextBytes(16), BackupCredentialType.MESSAGES, BackupLevel.PAID))
|
||||
.toList();
|
||||
for (int i = 0; i < backupUsers.size(); i++) {
|
||||
testClock.pin(days(i));
|
||||
@@ -919,7 +928,7 @@ public class BackupManagerTest {
|
||||
final List<ExpiredBackup> expired = backupManager
|
||||
.getExpiredBackups(1, Schedulers.immediate(), day)
|
||||
.collectList()
|
||||
.block();
|
||||
.blockOptional().orElseThrow();
|
||||
|
||||
// all the backups tht should be expired at t=i should be returned (ones with expiration time 0,1,...i-1)
|
||||
assertThat(expired.size()).isEqualTo(expectedHashes.size());
|
||||
@@ -1153,7 +1162,7 @@ public class BackupManagerTest {
|
||||
* Retrieve an existing BackupUser from the database
|
||||
*/
|
||||
private AuthenticatedBackupUser retrieveBackupUser(final byte[] backupId, final BackupCredentialType credentialType, final BackupLevel backupLevel) {
|
||||
final BackupsDb.AuthenticationData authData = backupsDb.retrieveAuthenticationData(backupId).join().get();
|
||||
final BackupsDb.AuthenticationData authData = backupsDb.retrieveAuthenticationData(backupId).join().orElseThrow();
|
||||
return new AuthenticatedBackupUser(backupId, credentialType, backupLevel, authData.backupDir(), authData.mediaDir(), null);
|
||||
}
|
||||
|
||||
|
||||
@@ -16,10 +16,7 @@ import java.time.temporal.ChronoUnit;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Stream;
|
||||
import org.assertj.core.util.Streams;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
@@ -57,22 +54,30 @@ public class BackupsDbTest {
|
||||
@Test
|
||||
public void trackMediaStats() {
|
||||
final AuthenticatedBackupUser backupUser = backupUser(TestRandomUtil.nextBytes(16), BackupCredentialType.MEDIA, BackupLevel.PAID);
|
||||
// add at least one message backup so we can describe it
|
||||
backupsDb.addMessageBackup(backupUser).join();
|
||||
int total = 0;
|
||||
for (int i = 0; i < 5; i++) {
|
||||
this.backupsDb.trackMedia(backupUser, 1, i).join();
|
||||
total += i;
|
||||
final BackupsDb.BackupDescription description = this.backupsDb.describeBackup(backupUser).join();
|
||||
assertThat(description.mediaUsedSpace().get()).isEqualTo(total);
|
||||
final StoredBackupAttributes storedAttrs = backupsDb.ttlRefresh(backupUser).join();
|
||||
assertThat(description.mediaUsedSpace().orElseThrow())
|
||||
.isEqualTo(total)
|
||||
.isEqualTo(storedAttrs.bytesUsed());
|
||||
assertThat(storedAttrs.numObjects()).isEqualTo(i + 1);
|
||||
}
|
||||
|
||||
|
||||
for (int i = 0; i < 5; i++) {
|
||||
this.backupsDb.trackMedia(backupUser, -1, -i).join();
|
||||
total -= i;
|
||||
final BackupsDb.BackupDescription description = this.backupsDb.describeBackup(backupUser).join();
|
||||
assertThat(description.mediaUsedSpace().get()).isEqualTo(total);
|
||||
final StoredBackupAttributes storedAttrs = backupsDb.ttlRefresh(backupUser).join();
|
||||
assertThat(description.mediaUsedSpace().orElseThrow())
|
||||
.isEqualTo(total)
|
||||
.isEqualTo(storedAttrs.bytesUsed());
|
||||
assertThat(storedAttrs.numObjects()).isEqualTo(5 - i - 1);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@@ -236,7 +241,7 @@ public class BackupsDbTest {
|
||||
backupsDb.trackMedia(users.get(1), 10, 100).join();
|
||||
backupsDb.trackMedia(users.get(2), 1, 1000).join();
|
||||
|
||||
final List<StoredBackupAttributes> sbms = backupsDb.listBackupAttributes(1, Schedulers.immediate())
|
||||
final List<StoredBackupAttributes> sbms = backupsDb.listBackupAttributes(1)
|
||||
.sort(Comparator.comparing(StoredBackupAttributes::lastRefresh))
|
||||
.collectList()
|
||||
.block();
|
||||
|
||||
+21
@@ -182,6 +182,27 @@ public class ArchiveControllerTest {
|
||||
backupAuthTestUtil.getRequest(mediaBackupKey, aci));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({
|
||||
"true, 0",
|
||||
"false, 1",
|
||||
"false, 12345"
|
||||
})
|
||||
public void backupIdLimits(boolean hasPermits, long waitSeconds) {
|
||||
when(backupAuthManager.checkBackupIdRotationLimit(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(
|
||||
new BackupAuthManager.BackupIdRotationLimit(hasPermits, Duration.ofSeconds(waitSeconds))));
|
||||
|
||||
final ArchiveController.BackupIdLimitResponse response = resources.getJerseyTest()
|
||||
.target("v1/archives/backupid/limits")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.get(ArchiveController.BackupIdLimitResponse.class);
|
||||
|
||||
assertThat(response.hasPermitsRemaining()).isEqualTo(hasPermits);
|
||||
assertThat(response.retryAfterSeconds()).isEqualTo(waitSeconds);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void redeemReceipt() throws InvalidInputException, VerificationFailedException {
|
||||
final ServerSecretParams params = ServerSecretParams.generate();
|
||||
|
||||
+11
-3
@@ -63,16 +63,18 @@ import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialResponse;
|
||||
import org.signal.libsignal.zkgroup.receipts.ReceiptSerial;
|
||||
import org.signal.libsignal.zkgroup.receipts.ServerZkReceiptOperations;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupManager;
|
||||
import org.whispersystems.textsecuregcm.badges.BadgeTranslator;
|
||||
import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.SubscriptionConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicBackupConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.controllers.SubscriptionController.GetBankMandateResponse;
|
||||
import org.whispersystems.textsecuregcm.controllers.SubscriptionController.GetSubscriptionConfigurationResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.Badge;
|
||||
import org.whispersystems.textsecuregcm.entities.BadgeSvg;
|
||||
import org.whispersystems.textsecuregcm.mappers.CompletionExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.SubscriptionExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.storage.IssuedReceiptsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.OneTimeDonationsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.PaymentTime;
|
||||
@@ -112,6 +114,7 @@ class SubscriptionControllerTest {
|
||||
|
||||
private static final ObjectMapper YAML_MAPPER = SystemMapper.yamlMapper();
|
||||
|
||||
private static final long MAX_TOTAL_BACKUP_MEDIA_BYTES = 1234L;
|
||||
private static final SubscriptionConfiguration SUBSCRIPTION_CONFIG = ConfigHelper.getSubscriptionConfig();
|
||||
private static final OneTimeDonationConfiguration ONETIME_CONFIG = ConfigHelper.getOneTimeConfig();
|
||||
private static final Subscriptions SUBSCRIPTIONS = mock(Subscriptions.class);
|
||||
@@ -129,11 +132,12 @@ class SubscriptionControllerTest {
|
||||
private static final OneTimeDonationsManager ONE_TIME_DONATIONS_MANAGER = mock(OneTimeDonationsManager.class);
|
||||
private static final BadgeTranslator BADGE_TRANSLATOR = mock(BadgeTranslator.class);
|
||||
private static final BankMandateTranslator BANK_MANDATE_TRANSLATOR = mock(BankMandateTranslator.class);
|
||||
private static final DynamicConfigurationManager<DynamicConfiguration> DYNAMIC_CONFIGURATION_MANAGER = mock(DynamicConfigurationManager.class);
|
||||
private final static SubscriptionController SUBSCRIPTION_CONTROLLER = new SubscriptionController(CLOCK,
|
||||
SUBSCRIPTION_CONFIG, ONETIME_CONFIG,
|
||||
new SubscriptionManager(SUBSCRIPTIONS, List.of(STRIPE_MANAGER, BRAINTREE_MANAGER, PLAY_MANAGER, APPSTORE_MANAGER),
|
||||
ZK_OPS, ISSUED_RECEIPTS_MANAGER), STRIPE_MANAGER, BRAINTREE_MANAGER, PLAY_MANAGER, APPSTORE_MANAGER,
|
||||
BADGE_TRANSLATOR, BANK_MANDATE_TRANSLATOR);
|
||||
BADGE_TRANSLATOR, BANK_MANDATE_TRANSLATOR, DYNAMIC_CONFIGURATION_MANAGER);
|
||||
private static final OneTimeDonationController ONE_TIME_CONTROLLER = new OneTimeDonationController(CLOCK,
|
||||
ONETIME_CONFIG, STRIPE_MANAGER, BRAINTREE_MANAGER, ZK_OPS, ISSUED_RECEIPTS_MANAGER, ONE_TIME_DONATIONS_MANAGER);
|
||||
private static final ResourceExtension RESOURCE_EXTENSION = ResourceExtension.builder()
|
||||
@@ -154,6 +158,10 @@ class SubscriptionControllerTest {
|
||||
|
||||
when(STRIPE_MANAGER.getProvider()).thenReturn(PaymentProvider.STRIPE);
|
||||
when(BRAINTREE_MANAGER.getProvider()).thenReturn(PaymentProvider.BRAINTREE);
|
||||
final DynamicConfiguration dynamicConfiguration = mock(DynamicConfiguration.class);
|
||||
when(dynamicConfiguration.getBackupConfiguration())
|
||||
.thenReturn(new DynamicBackupConfiguration(null, null, null, null, MAX_TOTAL_BACKUP_MEDIA_BYTES));
|
||||
when(DYNAMIC_CONFIGURATION_MANAGER.getConfiguration()).thenReturn(dynamicConfiguration);
|
||||
|
||||
List.of(STRIPE_MANAGER, BRAINTREE_MANAGER)
|
||||
.forEach(manager -> when(manager.supportsPaymentMethod(any()))
|
||||
@@ -1223,7 +1231,7 @@ class SubscriptionControllerTest {
|
||||
});
|
||||
|
||||
assertThat(response.backup().levels()).containsOnlyKeys("201").extractingByKey("201").satisfies(configuration -> {
|
||||
assertThat(configuration.storageAllowanceBytes()).isEqualTo(BackupManager.MAX_TOTAL_BACKUP_MEDIA_BYTES);
|
||||
assertThat(configuration.storageAllowanceBytes()).isEqualTo(MAX_TOTAL_BACKUP_MEDIA_BYTES);
|
||||
assertThat(configuration.playProductId()).isEqualTo("testPlayProductId");
|
||||
assertThat(configuration.mediaTtlDays()).isEqualTo(40);
|
||||
});
|
||||
|
||||
+77
-3
@@ -47,6 +47,8 @@ import org.glassfish.jersey.server.monitoring.RequestEvent;
|
||||
import org.glassfish.jersey.uri.UriTemplate;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.whispersystems.textsecuregcm.filters.RemoteAddressFilter;
|
||||
import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
|
||||
@@ -129,11 +131,12 @@ class MetricsRequestEventListenerTest {
|
||||
tags.add(tag);
|
||||
}
|
||||
|
||||
assertEquals(6, tags.size());
|
||||
assertEquals(7, tags.size());
|
||||
assertTrue(tags.contains(Tag.of(MetricsRequestEventListener.PATH_TAG, path)));
|
||||
assertTrue(tags.contains(Tag.of(MetricsRequestEventListener.METHOD_TAG, method)));
|
||||
assertTrue(tags.contains(Tag.of(MetricsRequestEventListener.STATUS_CODE_TAG, String.valueOf(statusCode))));
|
||||
assertTrue(tags.contains(Tag.of(MetricsRequestEventListener.TRAFFIC_SOURCE_TAG, TRAFFIC_SOURCE.name().toLowerCase())));
|
||||
assertTrue(tags.contains(Tag.of(MetricsRequestEventListener.AUTHENTICATED_TAG, "false")));
|
||||
assertTrue(tags.contains(Tag.of(UserAgentTagUtil.PLATFORM_TAG, "android")));
|
||||
assertTrue(tags.contains(Tag.of(UserAgentTagUtil.LIBSIGNAL_TAG, "true")));
|
||||
}
|
||||
@@ -196,11 +199,12 @@ class MetricsRequestEventListenerTest {
|
||||
tags.add(tag);
|
||||
}
|
||||
|
||||
assertEquals(6, tags.size());
|
||||
assertEquals(7, tags.size());
|
||||
assertTrue(tags.contains(Tag.of(MetricsRequestEventListener.PATH_TAG, "/v1/test/hello")));
|
||||
assertTrue(tags.contains(Tag.of(MetricsRequestEventListener.METHOD_TAG, "GET")));
|
||||
assertTrue(tags.contains(Tag.of(MetricsRequestEventListener.STATUS_CODE_TAG, String.valueOf(200))));
|
||||
assertTrue(tags.contains(Tag.of(MetricsRequestEventListener.TRAFFIC_SOURCE_TAG, TRAFFIC_SOURCE.name().toLowerCase())));
|
||||
assertTrue(tags.contains(Tag.of(MetricsRequestEventListener.AUTHENTICATED_TAG, "true")));
|
||||
assertTrue(tags.contains(Tag.of(UserAgentTagUtil.PLATFORM_TAG, "android")));
|
||||
assertTrue(tags.contains(Tag.of(UserAgentTagUtil.LIBSIGNAL_TAG, "false")));
|
||||
}
|
||||
@@ -261,11 +265,81 @@ class MetricsRequestEventListenerTest {
|
||||
tags.add(tag);
|
||||
}
|
||||
|
||||
assertEquals(6, tags.size());
|
||||
assertEquals(7, tags.size());
|
||||
assertTrue(tags.contains(Tag.of(MetricsRequestEventListener.PATH_TAG, "/v1/test/hello")));
|
||||
assertTrue(tags.contains(Tag.of(MetricsRequestEventListener.METHOD_TAG, "GET")));
|
||||
assertTrue(tags.contains(Tag.of(MetricsRequestEventListener.STATUS_CODE_TAG, String.valueOf(200))));
|
||||
assertTrue(tags.contains(Tag.of(MetricsRequestEventListener.TRAFFIC_SOURCE_TAG, TRAFFIC_SOURCE.name().toLowerCase())));
|
||||
assertTrue(tags.contains(Tag.of(MetricsRequestEventListener.AUTHENTICATED_TAG, "true")));
|
||||
assertTrue(tags.contains(Tag.of(UserAgentTagUtil.PLATFORM_TAG, "unrecognized")));
|
||||
assertTrue(tags.contains(Tag.of(UserAgentTagUtil.LIBSIGNAL_TAG, "false")));
|
||||
}
|
||||
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void testAuthenticated(final boolean authenticated) throws IOException {
|
||||
final MetricsApplicationEventListener applicationEventListener = mock(MetricsApplicationEventListener.class);
|
||||
when(applicationEventListener.onRequest(any())).thenReturn(listener);
|
||||
|
||||
final ResourceConfig resourceConfig = new DropwizardResourceConfig();
|
||||
resourceConfig.register(applicationEventListener);
|
||||
resourceConfig.register(new TestResource());
|
||||
resourceConfig.register(new WebSocketSessionContextValueFactoryProvider.Binder());
|
||||
resourceConfig.register(new WebsocketAuthValueFactoryProvider.Binder<>(TestPrincipal.class));
|
||||
resourceConfig.register(new JacksonMessageBodyProvider(new ObjectMapper()));
|
||||
|
||||
final ApplicationHandler applicationHandler = new ApplicationHandler(resourceConfig);
|
||||
final WebsocketRequestLog requestLog = mock(WebsocketRequestLog.class);
|
||||
final Optional<TestPrincipal> maybePrincipal = authenticated ? TestPrincipal.authenticatedTestPrincipal("foo") : Optional.empty();
|
||||
final WebSocketResourceProvider<TestPrincipal> provider = new WebSocketResourceProvider<>("127.0.0.1",
|
||||
RemoteAddressFilter.REMOTE_ADDRESS_ATTRIBUTE_NAME, applicationHandler, requestLog, maybePrincipal,
|
||||
new ProtobufWebSocketMessageFactory(), Optional.empty(), Duration.ofMillis(30000));
|
||||
|
||||
final Session session = mock(Session.class);
|
||||
final RemoteEndpoint remoteEndpoint = mock(RemoteEndpoint.class);
|
||||
final UpgradeRequest request = mock(UpgradeRequest.class);
|
||||
|
||||
when(session.getUpgradeRequest()).thenReturn(request);
|
||||
when(session.getRemote()).thenReturn(remoteEndpoint);
|
||||
|
||||
final ArgumentCaptor<Iterable<Tag>> tagCaptor = ArgumentCaptor.forClass(Iterable.class);
|
||||
when(meterRegistry.counter(eq(MetricsRequestEventListener.REQUEST_COUNTER_NAME), any(Iterable.class))).thenReturn(
|
||||
counter);
|
||||
when(meterRegistry.counter(eq(MetricsRequestEventListener.RESPONSE_BYTES_COUNTER_NAME), any(Iterable.class)))
|
||||
.thenReturn(responseBytesCounter);
|
||||
when(meterRegistry.counter(eq(MetricsRequestEventListener.REQUEST_BYTES_COUNTER_NAME), any(Iterable.class)))
|
||||
.thenReturn(requestBytesCounter);
|
||||
|
||||
provider.onWebSocketConnect(session);
|
||||
|
||||
final byte[] message = new ProtobufWebSocketMessageFactory().createRequest(Optional.of(111L), "GET", "/v1/test/hello",
|
||||
new LinkedList<>(), Optional.empty()).toByteArray();
|
||||
|
||||
provider.onWebSocketBinary(message, 0, message.length);
|
||||
|
||||
final ArgumentCaptor<ByteBuffer> responseBytesCaptor = ArgumentCaptor.forClass(ByteBuffer.class);
|
||||
verify(remoteEndpoint).sendBytes(responseBytesCaptor.capture(), any(WriteCallback.class));
|
||||
|
||||
SubProtocol.WebSocketResponseMessage response = getResponse(responseBytesCaptor);
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
|
||||
verify(meterRegistry).counter(eq(MetricsRequestEventListener.REQUEST_COUNTER_NAME), tagCaptor.capture());
|
||||
|
||||
final Iterable<Tag> tagIterable = tagCaptor.getValue();
|
||||
final Set<Tag> tags = new HashSet<>();
|
||||
|
||||
for (final Tag tag : tagIterable) {
|
||||
tags.add(tag);
|
||||
}
|
||||
|
||||
assertEquals(7, tags.size());
|
||||
assertTrue(tags.contains(Tag.of(MetricsRequestEventListener.PATH_TAG, "/v1/test/hello")));
|
||||
assertTrue(tags.contains(Tag.of(MetricsRequestEventListener.METHOD_TAG, "GET")));
|
||||
assertTrue(tags.contains(Tag.of(MetricsRequestEventListener.STATUS_CODE_TAG, String.valueOf(200))));
|
||||
assertTrue(tags.contains(Tag.of(MetricsRequestEventListener.TRAFFIC_SOURCE_TAG, TRAFFIC_SOURCE.name().toLowerCase())));
|
||||
assertTrue(tags.contains(Tag.of(MetricsRequestEventListener.AUTHENTICATED_TAG, String.valueOf(authenticated))));
|
||||
assertTrue(tags.contains(Tag.of(UserAgentTagUtil.PLATFORM_TAG, "unrecognized")));
|
||||
assertTrue(tags.contains(Tag.of(UserAgentTagUtil.LIBSIGNAL_TAG, "false")));
|
||||
}
|
||||
|
||||
+25
-2
@@ -14,6 +14,8 @@ import io.micrometer.core.instrument.Meter;
|
||||
import io.micrometer.core.instrument.MeterRegistry;
|
||||
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
import org.assertj.core.api.AbstractStringAssert;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
@@ -37,7 +39,7 @@ class MetricsUtilTest {
|
||||
@ValueSource(booleans = {true, false})
|
||||
void lettuceTagRejection(final boolean enableLettuceRemoteTag) {
|
||||
final DynamicConfiguration dynamicConfiguration = mock(DynamicConfiguration.class);
|
||||
final DynamicMetricsConfiguration metricsConfiguration = new DynamicMetricsConfiguration(enableLettuceRemoteTag, false);
|
||||
final DynamicMetricsConfiguration metricsConfiguration = new DynamicMetricsConfiguration(enableLettuceRemoteTag, false, null);
|
||||
when(dynamicConfiguration.getMetricsConfiguration()).thenReturn(metricsConfiguration);
|
||||
@SuppressWarnings("unchecked") final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager =
|
||||
mock(DynamicConfigurationManager.class);
|
||||
@@ -70,7 +72,7 @@ class MetricsUtilTest {
|
||||
mock(DynamicConfigurationManager.class);
|
||||
|
||||
final DynamicConfiguration dynamicConfiguration = mock(DynamicConfiguration.class);
|
||||
final DynamicMetricsConfiguration metricsConfiguration = new DynamicMetricsConfiguration(false, enableAwsSdkMetrics);
|
||||
final DynamicMetricsConfiguration metricsConfiguration = new DynamicMetricsConfiguration(false, enableAwsSdkMetrics, null);
|
||||
|
||||
when(dynamicConfigurationManager.getConfiguration()).thenReturn(dynamicConfiguration);
|
||||
when(dynamicConfiguration.getMetricsConfiguration()).thenReturn(metricsConfiguration);
|
||||
@@ -81,4 +83,25 @@ class MetricsUtilTest {
|
||||
|
||||
assertThat(registry.getMeters()).hasSize(enableAwsSdkMetrics ? 1 : 0);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans={true, false})
|
||||
void datadogAllowList(boolean useAllowlist) {
|
||||
@SuppressWarnings("unchecked") final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager =
|
||||
mock(DynamicConfigurationManager.class);
|
||||
|
||||
final DynamicConfiguration dynamicConfiguration = mock(DynamicConfiguration.class);
|
||||
final DynamicMetricsConfiguration metricsConfiguration = new DynamicMetricsConfiguration(true, true, useAllowlist ? Set.of("chat.ImportantMetrics.messages") : null);
|
||||
|
||||
when(dynamicConfigurationManager.getConfiguration()).thenReturn(dynamicConfiguration);
|
||||
when(dynamicConfiguration.getMetricsConfiguration()).thenReturn(metricsConfiguration);
|
||||
|
||||
final MeterRegistry registry = new SimpleMeterRegistry();
|
||||
MetricsUtil.configureDatadogAllowList(registry.config(), dynamicConfigurationManager);
|
||||
registry.counter("chat.ImportantMetrics.messages").increment();
|
||||
registry.counter("chat.ChattyMetrics.days_since_last_incident").increment();
|
||||
|
||||
assertThat(registry.getMeters()).hasSize(useAllowlist ? 1 : 2);
|
||||
}
|
||||
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
|
||||
import com.google.api.services.androidpublisher.model.Money;
|
||||
import org.assertj.core.api.Assertions;
|
||||
import org.assertj.core.data.Percentage;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class SubscriptionCurrencyUtilTest {
|
||||
|
||||
@Test
|
||||
void convertGoogleMoneyToApiAmount() {
|
||||
Money money = new Money();
|
||||
money.setCurrencyCode("USD");
|
||||
money.setUnits(4L);
|
||||
|
||||
BigDecimal amt = SubscriptionCurrencyUtil.convertGoogleMoneyToApiAmount(money);
|
||||
Assertions.assertThat(amt).isCloseTo(BigDecimal.valueOf(400), Percentage.withPercentage(0.0001));
|
||||
|
||||
money.setNanos(990000000);
|
||||
amt = SubscriptionCurrencyUtil.convertGoogleMoneyToApiAmount(money);
|
||||
Assertions.assertThat(amt).isCloseTo(BigDecimal.valueOf(499), Percentage.withPercentage(0.0001));
|
||||
|
||||
}
|
||||
}
|
||||
+3
@@ -83,6 +83,9 @@ class FinishPushNotificationExperimentCommandTest {
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null);
|
||||
|
||||
//noinspection unchecked
|
||||
|
||||
+3
@@ -65,6 +65,9 @@ class NotifyIdleDevicesCommandTest {
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null);
|
||||
|
||||
this.idleDeviceNotificationScheduler = idleDeviceNotificationScheduler;
|
||||
|
||||
+3
@@ -50,6 +50,9 @@ class RegenerateSecondaryDynamoDbTableDataCommandTest {
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
dynamoDbRecoveryManager);
|
||||
|
||||
namespace = new Namespace(Map.of(
|
||||
|
||||
+3
@@ -72,6 +72,9 @@ class StartPushNotificationExperimentCommandTest {
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null);
|
||||
}
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ stripe.idempotencyKeyGenerator: abcdefg12345678= # base64 for creating request i
|
||||
|
||||
braintree.privateKey: unset
|
||||
|
||||
# The below private key was key generated exclusively for testing purposes. Do not use it in any other context.
|
||||
# The below private key was generated exclusively for testing purposes. Do not use it in any other context.
|
||||
googlePlayBilling.credentialsJson: |
|
||||
{ "type": "service_account", "client_id": "client_id", "client_email": "fake@example.com",
|
||||
"private_key_id": "id",
|
||||
@@ -39,7 +39,7 @@ googlePlayBilling.credentialsJson: |
|
||||
TQkqmVUmgKKvCFTPWwCgeIOD
|
||||
-----END PRIVATE KEY-----" }
|
||||
|
||||
# The below private key was key generated exclusively for testing purposes. Do not use it in any other context.
|
||||
# The below private key was generated exclusively for testing purposes. Do not use it in any other context.
|
||||
appleAppStore.encodedKey: |
|
||||
-----BEGIN PRIVATE KEY-----
|
||||
MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgF32wH6zG3GFMBs38
|
||||
@@ -58,7 +58,7 @@ svrb.userIdTokenSharedSecret: bbcdefghijklmnopqrstuvwxyz0123456789ABCDEFG= # bas
|
||||
|
||||
tus.userAuthenticationTokenSharedSecret: abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG=
|
||||
|
||||
# The below private key was key generated exclusively for testing purposes. Do not use it in any other context.
|
||||
# The below private key was generated exclusively for testing purposes. Do not use it in any other context.
|
||||
gcpAttachments.rsaSigningKey: |
|
||||
-----BEGIN PRIVATE KEY-----
|
||||
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCrfHLw9zr/8mTX
|
||||
@@ -91,7 +91,7 @@ gcpAttachments.rsaSigningKey: |
|
||||
|
||||
apn.teamId: team-id
|
||||
apn.keyId: key-id
|
||||
# The below private key was key generated exclusively for testing purposes. Do not use it in any other context.
|
||||
# The below private key was generated exclusively for testing purposes. Do not use it in any other context.
|
||||
apn.signingKey: |
|
||||
-----BEGIN PRIVATE KEY-----
|
||||
MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgxIXnNiHH35DDbKHY
|
||||
@@ -99,7 +99,7 @@ apn.signingKey: |
|
||||
7NSEd5L+df4M7V9YxxDoYY+UHd8B/KmrWR29SVIRLncSULgfSnHnHvoH
|
||||
-----END PRIVATE KEY-----
|
||||
|
||||
# The below private key was key generated exclusively for testing purposes. Do not use it in any other context.
|
||||
# The below private key was generated exclusively for testing purposes. Do not use it in any other context.
|
||||
fcm.credentials: |
|
||||
{ "type": "service_account", "client_id": "client_id", "client_email": "fake@example.com",
|
||||
"private_key_id": "id",
|
||||
@@ -144,12 +144,11 @@ keyTransparencyService.clientPrivateKey: |
|
||||
7NSEd5L+df4M7V9YxxDoYY+UHd8B/KmrWR29SVIRLncSULgfSnHnHvoH
|
||||
-----END PRIVATE KEY-----
|
||||
|
||||
# The below private key was key generated exclusively for testing purposes. Do not use it in any other context.
|
||||
# ca:
|
||||
# Public key : BVDuaR1ZT/5M26nSvFN1XjN4qFqVfwynt03l/GyK2GtP
|
||||
# Private key: 0Ie2/CIxfidwhS+uKSckb2YgtRR7UBLkecHNG2ARiW8=
|
||||
unidentifiedDelivery.certificate: CikIp/SIvwESIQWXK5ikKQdvB7XpwPowV4djRj6Ni0I9MO12AVNpzQ9DDBJApovqX/gmIc+ukn4YeYtCsk9Q0EoDoXAZPD0D5vflcnncUs2fFLEQLlnSZ/ckXVChZByyuiNiegtl468+A+u5gw==
|
||||
unidentifiedDelivery.privateKey: UKRdvrnxcy1hcILN7RHqUG40/mUd/ZnKkqhQToN4K1U=
|
||||
# The below private keys are exclusively for testing purposes. Do not use them in any other context.
|
||||
# Trust root for the certificate in test.yml:
|
||||
# Public key : BS/lfaNHzWJDFSjarF+7KQcw//aEr8TPwu2QmV9Yyzt0
|
||||
# Private key: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=
|
||||
unidentifiedDelivery.privateKey: //////////////////////////////////////////8=
|
||||
|
||||
storageService.userAuthenticationTokenSharedSecret: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=
|
||||
|
||||
|
||||
@@ -305,7 +305,7 @@ openTelemetry:
|
||||
url: http://127.0.0.1:4318/
|
||||
|
||||
unidentifiedDelivery:
|
||||
certificate: CgIIAQ==
|
||||
certificate: CikI14bfmgcSIQWEfA0sN1I082XmYJVRh6NzWg92E9FgnTpqTYxTrqpaIhJA4LnrrN/Dqign95JLaXeE0cJeRMoF3UM+GjjcY4LrJzDUGcqaJQsb6dWpRj5h79Z4F3epG4PJe4RNAUIG4oKXhQ==
|
||||
privateKey: secret://unidentifiedDelivery.privateKey
|
||||
expiresDays: 7
|
||||
|
||||
|
||||
+1
-1
Submodule spam-filter updated: b7f042f993...2be390e5b9.
+8
@@ -28,6 +28,10 @@ public class WebSocketConfiguration {
|
||||
@JsonProperty
|
||||
private int maxTextMessageSize = 512 * 1024;
|
||||
|
||||
@Valid
|
||||
@JsonProperty
|
||||
private boolean disablePerMessageDeflate = false;
|
||||
|
||||
public WebsocketRequestLoggerFactory getRequestLog() {
|
||||
return requestLog;
|
||||
}
|
||||
@@ -39,4 +43,8 @@ public class WebSocketConfiguration {
|
||||
public int getMaxTextMessageSize() {
|
||||
return maxTextMessageSize;
|
||||
}
|
||||
|
||||
public boolean isDisablePerMessageDeflate() {
|
||||
return disablePerMessageDeflate;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user