mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-12-01 09:16:47 +00:00
Compare commits
42
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
63f892add1 | ||
|
|
6e42b2898c | ||
|
|
9384813752 | ||
|
|
70ac4ad139 | ||
|
|
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 | ||
|
|
b2dd315177 | ||
|
|
dc3920a99c | ||
|
|
b8e8fd3313 | ||
|
|
a5423b6e21 | ||
|
|
89b37015c6 | ||
|
|
2af3088571 | ||
|
|
774cc52b61 |
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 }}
|
||||
|
||||
@@ -13,16 +13,21 @@ jobs:
|
||||
timeout-minutes: 20
|
||||
|
||||
services:
|
||||
foundationdb:
|
||||
foundationdb0:
|
||||
# Note: this should generally match the version of the FoundationDB SERVER deployed in production; it's okay if
|
||||
# it's a little behind the CLIENT version.
|
||||
image: foundationdb/foundationdb:7.3.62
|
||||
options: --name foundationdb
|
||||
options: --name foundationdb0
|
||||
foundationdb1:
|
||||
# Note: this should generally match the version of the FoundationDB SERVER deployed in production; it's okay if
|
||||
# it's a little behind the CLIENT version.
|
||||
image: foundationdb/foundationdb:7.3.62
|
||||
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
|
||||
@@ -49,12 +54,14 @@ jobs:
|
||||
|
||||
# ca-certificates: required for AWS CRT client
|
||||
apt update && apt install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin ca-certificates
|
||||
- name: Configure FoundationDB database
|
||||
run: docker exec foundationdb /usr/bin/fdbcli --exec 'configure new single memory'
|
||||
- name: Configure FoundationDB0 database
|
||||
run: docker exec foundationdb0 /usr/bin/fdbcli --exec 'configure new single memory'
|
||||
- name: Configure FoundationDB1 database
|
||||
run: docker exec foundationdb1 /usr/bin/fdbcli --exec 'configure new single memory'
|
||||
- name: Download and install FoundationDB client
|
||||
run: |
|
||||
./mvnw -e -B -Pexclude-spam-filter clean prepare-package -DskipTests=true
|
||||
cp service/target/jib-extra/usr/lib/libfdb_c.x86_64.so /usr/lib/libfdb_c.x86_64.so
|
||||
ldconfig
|
||||
- name: Build with Maven
|
||||
run: ./mvnw -e -B clean verify -DfoundationDb.serviceContainerName=foundationdb
|
||||
run: ./mvnw -e -B clean verify -DfoundationDb.serviceContainerNamePrefix=foundationdb
|
||||
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>
|
||||
|
||||
@@ -3,6 +3,7 @@ datadog.apiKey: unset
|
||||
stripe.apiKey: unset
|
||||
stripe.idempotencyKeyGenerator: abcdefg12345678= # base64 for creating request idempotency hash
|
||||
|
||||
braintree.publicKey: unset
|
||||
braintree.privateKey: unset
|
||||
|
||||
googlePlayBilling.credentialsJson: |
|
||||
|
||||
@@ -57,7 +57,7 @@ stripe:
|
||||
|
||||
braintree:
|
||||
merchantId: unset
|
||||
publicKey: unset
|
||||
publicKey: secret://braintree.publicKey
|
||||
privateKey: secret://braintree.privateKey
|
||||
environment: unset
|
||||
graphqlUrl: unset
|
||||
|
||||
+67
-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>
|
||||
@@ -445,6 +476,12 @@
|
||||
<artifactId>netty-codec-haproxy</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>io.netty</groupId>
|
||||
<artifactId>netty-transport-native-epoll</artifactId>
|
||||
<classifier>linux-x86_64</classifier>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.glassfish.jersey.test-framework</groupId>
|
||||
<artifactId>jersey-test-framework-core</artifactId>
|
||||
@@ -538,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);
|
||||
|
||||
@@ -542,11 +547,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
|
||||
// TODO: generally speaking this is a DynamoDB I/O executor for the accounts table; we should eventually have a general executor for speaking to the accounts table, but most of the server is still synchronous so this isn't widely useful yet
|
||||
ExecutorService batchIdentityCheckExecutor = ExecutorServiceBuilder.of(environment, "batchIdentityCheck").minThreads(32).maxThreads(32).build();
|
||||
ExecutorService subscriptionProcessorExecutor = ExecutorServiceBuilder.of(environment, "subscriptionProcessor")
|
||||
.maxThreads(availableProcessors) // mostly this is IO bound so tying to number of processors is tenuous at best
|
||||
.minThreads(availableProcessors) // mostly this is IO bound so tying to number of processors is tenuous at best
|
||||
.allowCoreThreadTimeOut(true).
|
||||
build();
|
||||
|
||||
ExecutorService receiptSenderExecutor = ExecutorServiceBuilder.of(environment, "receiptSender")
|
||||
.maxThreads(2)
|
||||
.minThreads(2)
|
||||
@@ -573,12 +574,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
.minThreads(2)
|
||||
.build();
|
||||
|
||||
ExecutorService googlePlayBillingExecutor = ManagedExecutors.newVirtualThreadPerTaskExecutor(
|
||||
"googlePlayBilling",
|
||||
config.getVirtualThreadConfiguration().maxConcurrentThreadsPerExecutor(),
|
||||
environment);
|
||||
ExecutorService appleAppStoreExecutor = ManagedExecutors.newVirtualThreadPerTaskExecutor(
|
||||
"appleAppStore",
|
||||
ExecutorService subscriptionProcessorExecutor = ManagedExecutors.newVirtualThreadPerTaskExecutor(
|
||||
"subscriptionProcessor",
|
||||
config.getVirtualThreadConfiguration().maxConcurrentThreadsPerExecutor(),
|
||||
environment);
|
||||
ExecutorService clientEventExecutor = ManagedExecutors.newVirtualThreadPerTaskExecutor(
|
||||
@@ -590,8 +587,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
config.getVirtualThreadConfiguration().maxConcurrentThreadsPerExecutor(),
|
||||
environment);
|
||||
|
||||
ScheduledExecutorService appleAppStoreRetryExecutor = ScheduledExecutorServiceBuilder.of(environment, "appleAppStoreRetry").threads(1).build();
|
||||
ScheduledExecutorService subscriptionProcessorRetryExecutor = ScheduledExecutorServiceBuilder.of(environment, "subscriptionProcessorRetry").threads(1).build();
|
||||
ScheduledExecutorService cloudflareTurnRetryExecutor = ScheduledExecutorServiceBuilder.of(environment, "cloudflareTurnRetry").threads(1).build();
|
||||
ScheduledExecutorService messagePollExecutor = ScheduledExecutorServiceBuilder.of(environment, "messagePollExecutor").threads(1).build();
|
||||
ScheduledExecutorService provisioningWebsocketTimeoutExecutor = ScheduledExecutorServiceBuilder.of(environment, "provisioningWebsocketTimeout").threads(1).build();
|
||||
@@ -745,25 +740,23 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
StripeManager stripeManager = new StripeManager(config.getStripe().apiKey().value(), subscriptionProcessorExecutor,
|
||||
config.getStripe().idempotencyKeyGenerator().value(), config.getStripe().boostDescription(), config.getStripe().supportedCurrenciesByPaymentMethod());
|
||||
BraintreeManager braintreeManager = new BraintreeManager(config.getBraintree().merchantId(),
|
||||
config.getBraintree().publicKey(), config.getBraintree().privateKey().value(),
|
||||
config.getBraintree().publicKey().value(), config.getBraintree().privateKey().value(),
|
||||
config.getBraintree().environment(),
|
||||
config.getBraintree().supportedCurrenciesByPaymentMethod(), config.getBraintree().merchantAccounts(),
|
||||
config.getBraintree().graphqlUrl(), currencyManager, config.getBraintree().pubSubPublisher().build(),
|
||||
config.getBraintree().circuitBreakerConfigurationName(), subscriptionProcessorExecutor,
|
||||
subscriptionProcessorRetryExecutor);
|
||||
config.getBraintree().circuitBreakerConfigurationName(), subscriptionProcessorExecutor);
|
||||
GooglePlayBillingManager googlePlayBillingManager = new GooglePlayBillingManager(
|
||||
new ByteArrayInputStream(config.getGooglePlayBilling().credentialsJson().value().getBytes(StandardCharsets.UTF_8)),
|
||||
config.getGooglePlayBilling().packageName(),
|
||||
config.getGooglePlayBilling().applicationName(),
|
||||
config.getGooglePlayBilling().productIdToLevel(),
|
||||
googlePlayBillingExecutor);
|
||||
config.getGooglePlayBilling().productIdToLevel());
|
||||
AppleAppStoreManager appleAppStoreManager = new AppleAppStoreManager(
|
||||
config.getAppleAppStore().env(), config.getAppleAppStore().bundleId(), config.getAppleAppStore().appAppleId(),
|
||||
config.getAppleAppStore().issuerId(), config.getAppleAppStore().keyId(),
|
||||
config.getAppleAppStore().encodedKey().value(), config.getAppleAppStore().subscriptionGroupId(),
|
||||
config.getAppleAppStore().productIdToLevel(),
|
||||
config.getAppleAppStore().appleRootCerts(),
|
||||
config.getAppleAppStore().retryConfigurationName(), appleAppStoreExecutor, appleAppStoreRetryExecutor);
|
||||
config.getAppleAppStore().retryConfigurationName());
|
||||
|
||||
environment.lifecycle().manage(apnSender);
|
||||
environment.lifecycle().manage(pushNotificationScheduler);
|
||||
@@ -818,7 +811,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
cdn3RemoteStorageManager,
|
||||
svrbCredentialsGenerator,
|
||||
secureValueRecoveryBClient,
|
||||
clock);
|
||||
clock,
|
||||
dynamicConfigurationManager);
|
||||
|
||||
final AppleDeviceChecks appleDeviceChecks = new AppleDeviceChecks(
|
||||
dynamoDbClient,
|
||||
@@ -1151,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));
|
||||
}
|
||||
@@ -1174,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(),
|
||||
@@ -1193,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);
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.auth;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.Iterator;
|
||||
import java.util.Objects;
|
||||
import java.util.stream.Stream;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
/// A validated range of days for which a credential may be issued.
|
||||
public class RedemptionRange implements Iterable<Instant> {
|
||||
|
||||
public static final Duration MAX_REDEMPTION_DURATION = Duration.ofDays(7);
|
||||
|
||||
/// The first day for which a credential should be issued
|
||||
private final LocalDate from;
|
||||
|
||||
/// The last day for which a credential should be issued
|
||||
private final LocalDate end;
|
||||
|
||||
private RedemptionRange(final LocalDate from, final LocalDate end) {
|
||||
this.from = from;
|
||||
this.end = end;
|
||||
}
|
||||
|
||||
/// Construct a {@link RedemptionRange} if the provided day bounds are valid.
|
||||
///
|
||||
/// The redemption bounds must satisfy:
|
||||
/// - `redemptionEnd` >= `redemptionStart`
|
||||
/// - `redemptionStart` and `redemptionEnd` are day-aligned
|
||||
/// - `redemptionStart` is yesterday or later
|
||||
/// - `redemptionEnd` is tomorrow + `MAX_REDEMPTION_DURATION` or earlier
|
||||
/// - The number of days requested is less than `MAX_REDEMPTION_DURATION`
|
||||
///
|
||||
/// @param clock Clock to use to get current day
|
||||
/// @param redemptionStart The first day included in the range
|
||||
/// @param redemptionEnd The last day included in the range
|
||||
/// @return A {@link RedemptionRange} that can be used to iterate each day between `redemptionStart` and
|
||||
/// `redemptionEnd`
|
||||
/// @throws IllegalArgumentException if the redemption bounds were not valid
|
||||
public static RedemptionRange inclusive(Clock clock, Instant redemptionStart, Instant redemptionEnd)
|
||||
throws IllegalArgumentException {
|
||||
final Instant today = clock.instant().truncatedTo(ChronoUnit.DAYS);
|
||||
final Instant yesterday = today.minus(Duration.ofDays(1));
|
||||
|
||||
if (redemptionStart.isAfter(redemptionEnd)) {
|
||||
throw new IllegalArgumentException("end of range must be after start of range");
|
||||
}
|
||||
|
||||
if (!redemptionStart.truncatedTo(ChronoUnit.DAYS).equals(redemptionStart)
|
||||
|| !redemptionEnd.truncatedTo(ChronoUnit.DAYS).equals(redemptionEnd)) {
|
||||
throw new IllegalArgumentException("timestamps must be day aligned");
|
||||
}
|
||||
|
||||
if (redemptionStart.isBefore(yesterday)) {
|
||||
throw new IllegalArgumentException("start of range too far in the past");
|
||||
}
|
||||
|
||||
if (redemptionEnd.isAfter(today.plus(MAX_REDEMPTION_DURATION).plus(Duration.ofDays(1)))) {
|
||||
throw new IllegalArgumentException("end of range too far in the future");
|
||||
}
|
||||
|
||||
if (redemptionEnd.isAfter(redemptionStart.plus(MAX_REDEMPTION_DURATION))) {
|
||||
throw new IllegalArgumentException("redemption window too large");
|
||||
}
|
||||
|
||||
return new RedemptionRange(
|
||||
LocalDate.ofInstant(redemptionStart, ZoneOffset.UTC),
|
||||
LocalDate.ofInstant(redemptionEnd, ZoneOffset.UTC));
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull Iterator<Instant> iterator() {
|
||||
final Instant fromInstant = from.atStartOfDay(ZoneOffset.UTC).toInstant();
|
||||
final Instant endInstant = end.atStartOfDay(ZoneOffset.UTC).toInstant();
|
||||
return Stream
|
||||
.iterate(fromInstant, redemptionTime -> redemptionTime.plus(Duration.ofDays(1)))
|
||||
.takeWhile(redemptionTime -> !redemptionTime.isAfter(endInstant))
|
||||
.iterator();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(final Object o) {
|
||||
if (o == null || getClass() != o.getClass()) {
|
||||
return false;
|
||||
}
|
||||
RedemptionRange that = (RedemptionRange) o;
|
||||
return Objects.equals(from, that.from) && Objects.equals(end, that.end);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(from, end);
|
||||
}
|
||||
}
|
||||
+35
-17
@@ -11,11 +11,14 @@ 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;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
import java.util.stream.Stream;
|
||||
import java.util.stream.StreamSupport;
|
||||
import javax.annotation.Nullable;
|
||||
import org.signal.libsignal.zkgroup.GenericServerSecretParams;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
@@ -29,8 +32,10 @@ import org.signal.libsignal.zkgroup.receipts.ReceiptSerial;
|
||||
import org.signal.libsignal.zkgroup.receipts.ServerZkReceiptOperations;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.RedemptionRange;
|
||||
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 +139,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) {}
|
||||
|
||||
/**
|
||||
@@ -148,15 +179,13 @@ public class BackupAuthManager {
|
||||
*
|
||||
* @param account The account to create the credentials for
|
||||
* @param credentialType The type of backup credentials to create
|
||||
* @param redemptionStart The day (must be truncated to a day boundary) the first credential should be valid
|
||||
* @param redemptionEnd The day (must be truncated to a day boundary) the last credential should be valid
|
||||
* @param redemptionRange The time range to return credentials for
|
||||
* @return Credentials and the day on which they may be redeemed
|
||||
*/
|
||||
public CompletableFuture<List<Credential>> getBackupAuthCredentials(
|
||||
final Account account,
|
||||
final BackupCredentialType credentialType,
|
||||
final Instant redemptionStart,
|
||||
final Instant redemptionEnd) {
|
||||
final RedemptionRange redemptionRange) {
|
||||
|
||||
// If the account has an expired payment, clear it before continuing
|
||||
if (hasExpiredVoucher(account)) {
|
||||
@@ -165,17 +194,7 @@ public class BackupAuthManager {
|
||||
if (hasExpiredVoucher(a)) {
|
||||
a.setBackupVoucher(null);
|
||||
}
|
||||
}).thenCompose(updated -> getBackupAuthCredentials(updated, credentialType, redemptionStart, redemptionEnd));
|
||||
}
|
||||
|
||||
final Instant startOfDay = clock.instant().truncatedTo(ChronoUnit.DAYS);
|
||||
if (redemptionStart.isAfter(redemptionEnd) ||
|
||||
redemptionStart.isBefore(startOfDay) ||
|
||||
redemptionEnd.isAfter(startOfDay.plus(MAX_REDEMPTION_DURATION)) ||
|
||||
!redemptionStart.equals(redemptionStart.truncatedTo(ChronoUnit.DAYS)) ||
|
||||
!redemptionEnd.equals(redemptionEnd.truncatedTo(ChronoUnit.DAYS))) {
|
||||
|
||||
throw Status.INVALID_ARGUMENT.withDescription("invalid redemption window").asRuntimeException();
|
||||
}).thenCompose(updated -> getBackupAuthCredentials(updated, credentialType, redemptionRange));
|
||||
}
|
||||
|
||||
// fetch the blinded backup-id the account should have previously committed to
|
||||
@@ -187,8 +206,7 @@ public class BackupAuthManager {
|
||||
|
||||
// create a credential for every day in the requested period
|
||||
final BackupAuthCredentialRequest credentialReq = new BackupAuthCredentialRequest(committedBytes);
|
||||
return CompletableFuture.completedFuture(Stream
|
||||
.iterate(redemptionStart, redemptionTime -> !redemptionTime.isAfter(redemptionEnd), curr -> curr.plus(Duration.ofDays(1)))
|
||||
return CompletableFuture.completedFuture(StreamSupport.stream(redemptionRange.spliterator(), false)
|
||||
.map(redemptionTime -> {
|
||||
// Check if the account has a voucher that's good for a certain receiptLevel at redemption time, otherwise
|
||||
// use the default receipt level
|
||||
|
||||
@@ -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) {
|
||||
|
||||
+1
-1
@@ -27,7 +27,7 @@ import org.whispersystems.textsecuregcm.subscriptions.PaymentMethod;
|
||||
* GraphQL HTTP client; if `null`, uses the global default configuration
|
||||
*/
|
||||
public record BraintreeConfiguration(@NotBlank String merchantId,
|
||||
@NotBlank String publicKey,
|
||||
@NotNull SecretString publicKey,
|
||||
@NotNull SecretString privateKey,
|
||||
@NotBlank String environment,
|
||||
@Valid @NotEmpty Map<PaymentMethod, Set<@NotBlank String>> supportedCurrenciesByPaymentMethod,
|
||||
|
||||
+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) {
|
||||
}
|
||||
+38
-1
@@ -45,6 +45,7 @@ import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.util.Arrays;
|
||||
import java.util.Base64;
|
||||
@@ -65,6 +66,7 @@ import org.signal.libsignal.zkgroup.backups.BackupCredentialType;
|
||||
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialPresentation;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
|
||||
import org.whispersystems.textsecuregcm.auth.RedemptionRange;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupAuthManager;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupManager;
|
||||
import org.whispersystems.textsecuregcm.backup.CopyParameters;
|
||||
@@ -163,6 +165,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)
|
||||
@@ -281,6 +311,13 @@ public class ArchiveController {
|
||||
final Map<BackupCredentialType, List<BackupAuthCredentialsResponse.BackupAuthCredential>> credentialsByType =
|
||||
new ConcurrentHashMap<>();
|
||||
|
||||
final RedemptionRange redemptionRange;
|
||||
try {
|
||||
redemptionRange = RedemptionRange.inclusive(Clock.systemUTC(), Instant.ofEpochSecond(startSeconds), Instant.ofEpochSecond(endSeconds));
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw new BadRequestException(e.getMessage());
|
||||
}
|
||||
|
||||
return accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier())
|
||||
.thenCompose(maybeAccount -> {
|
||||
final Account account = maybeAccount
|
||||
@@ -290,7 +327,7 @@ public class ArchiveController {
|
||||
.map(credentialType -> this.backupAuthManager.getBackupAuthCredentials(
|
||||
account,
|
||||
credentialType,
|
||||
Instant.ofEpochSecond(startSeconds), Instant.ofEpochSecond(endSeconds))
|
||||
redemptionRange)
|
||||
.thenAccept(credentials -> {
|
||||
backupMetrics.updateGetCredentialCounter(
|
||||
UserAgentTagUtil.getPlatformTag(userAgent),
|
||||
|
||||
+9
-17
@@ -24,7 +24,6 @@ import java.security.InvalidKeyException;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
@@ -36,6 +35,7 @@ import org.signal.libsignal.zkgroup.auth.ServerZkAuthOperations;
|
||||
import org.signal.libsignal.zkgroup.calllinks.CallLinkAuthCredentialResponse;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.CertificateGenerator;
|
||||
import org.whispersystems.textsecuregcm.auth.RedemptionRange;
|
||||
import org.whispersystems.textsecuregcm.entities.DeliveryCertificate;
|
||||
import org.whispersystems.textsecuregcm.entities.GroupCredentials;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
@@ -97,17 +97,13 @@ public class CertificateController {
|
||||
@QueryParam("redemptionStartSeconds") long startSeconds,
|
||||
@QueryParam("redemptionEndSeconds") long endSeconds) {
|
||||
|
||||
final Instant startOfDay = clock.instant().truncatedTo(ChronoUnit.DAYS);
|
||||
final Instant redemptionStart = Instant.ofEpochSecond(startSeconds);
|
||||
final Instant redemptionEnd = Instant.ofEpochSecond(endSeconds);
|
||||
|
||||
if (redemptionStart.isAfter(redemptionEnd) ||
|
||||
redemptionStart.isBefore(startOfDay) ||
|
||||
redemptionEnd.isAfter(startOfDay.plus(MAX_REDEMPTION_DURATION)) ||
|
||||
!redemptionStart.equals(redemptionStart.truncatedTo(ChronoUnit.DAYS)) ||
|
||||
!redemptionEnd.equals(redemptionEnd.truncatedTo(ChronoUnit.DAYS))) {
|
||||
|
||||
throw new BadRequestException();
|
||||
final RedemptionRange redemptionRange;
|
||||
try {
|
||||
final Instant redemptionStart = Instant.ofEpochSecond(startSeconds);
|
||||
final Instant redemptionEnd = Instant.ofEpochSecond(endSeconds);
|
||||
redemptionRange = RedemptionRange.inclusive(clock, redemptionStart, redemptionEnd);
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw new BadRequestException(e.getCause());
|
||||
}
|
||||
|
||||
final Account account = accountsManager.getByAccountIdentifier(auth.accountIdentifier())
|
||||
@@ -116,12 +112,10 @@ public class CertificateController {
|
||||
final List<GroupCredentials.GroupCredential> credentials = new ArrayList<>();
|
||||
final List<GroupCredentials.CallLinkAuthCredential> callLinkAuthCredentials = new ArrayList<>();
|
||||
|
||||
Instant redemption = redemptionStart;
|
||||
|
||||
final ServiceId.Aci aci = new ServiceId.Aci(account.getIdentifier(IdentityType.ACI));
|
||||
final ServiceId.Pni pni = new ServiceId.Pni(account.getIdentifier(IdentityType.PNI));
|
||||
|
||||
while (!redemption.isAfter(redemptionEnd)) {
|
||||
for (Instant redemption : redemptionRange) {
|
||||
AuthCredentialWithPniResponse authCredentialWithPni = serverZkAuthOperations.issueAuthCredentialWithPniZkc(aci, pni, redemption);
|
||||
credentials.add(new GroupCredentials.GroupCredential(
|
||||
authCredentialWithPni.serialize(),
|
||||
@@ -130,8 +124,6 @@ public class CertificateController {
|
||||
callLinkAuthCredentials.add(new GroupCredentials.CallLinkAuthCredential(
|
||||
CallLinkAuthCredentialResponse.issueCredential(aci, redemption, genericServerSecretParams).serialize(),
|
||||
redemption.getEpochSecond()));
|
||||
|
||||
redemption = redemption.plus(Duration.ofDays(1));
|
||||
}
|
||||
|
||||
return new GroupCredentials(credentials, callLinkAuthCredentials, pni.getRawUUID());
|
||||
|
||||
+2
-1
@@ -78,7 +78,8 @@ public class ChallengeController {
|
||||
AnswerCaptchaChallengeRequest.class}))})
|
||||
)
|
||||
@ApiResponse(responseCode = "200", description = "Indicates the challenge proof was accepted")
|
||||
@ApiResponse(responseCode = "428", description = "Submitted captcha token is invalid")
|
||||
@ApiResponse(responseCode = "400", description = "The request was invalid")
|
||||
@ApiResponse(responseCode = "428", description = "Submitted captcha token was not accepted")
|
||||
@ApiResponse(responseCode = "429", description = "Too many attempts", headers = @Header(
|
||||
name = "Retry-After",
|
||||
description = "If present, an positive integer indicating the number of seconds before a subsequent attempt could succeed"))
|
||||
|
||||
+51
-55
@@ -26,6 +26,7 @@ import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
import java.util.function.Function;
|
||||
import javax.annotation.Nonnull;
|
||||
import org.glassfish.jersey.server.ManagedAsync;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.VerificationFailedException;
|
||||
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialPresentation;
|
||||
@@ -86,64 +87,59 @@ public class DonationController {
|
||||
specific error message suitable for logging will be included as text/plain body
|
||||
""")
|
||||
@ApiResponse(responseCode = "429", description = "Rate limited.")
|
||||
public CompletionStage<Response> redeemReceipt(
|
||||
@ManagedAsync
|
||||
public Response redeemReceipt(
|
||||
@Auth final AuthenticatedDevice auth,
|
||||
@NotNull @Valid final RedeemReceiptRequest request) {
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
ReceiptCredentialPresentation receiptCredentialPresentation;
|
||||
try {
|
||||
receiptCredentialPresentation = receiptCredentialPresentationFactory
|
||||
.build(request.getReceiptCredentialPresentation());
|
||||
} catch (InvalidInputException e) {
|
||||
return CompletableFuture.completedFuture(Response.status(Status.BAD_REQUEST)
|
||||
.entity("invalid receipt credential presentation")
|
||||
.type(MediaType.TEXT_PLAIN_TYPE)
|
||||
.build());
|
||||
ReceiptCredentialPresentation receiptCredentialPresentation;
|
||||
try {
|
||||
receiptCredentialPresentation = receiptCredentialPresentationFactory
|
||||
.build(request.getReceiptCredentialPresentation());
|
||||
} catch (InvalidInputException e) {
|
||||
return Response.status(Status.BAD_REQUEST)
|
||||
.entity("invalid receipt credential presentation")
|
||||
.type(MediaType.TEXT_PLAIN_TYPE)
|
||||
.build();
|
||||
}
|
||||
try {
|
||||
serverZkReceiptOperations.verifyReceiptCredentialPresentation(receiptCredentialPresentation);
|
||||
} catch (VerificationFailedException e) {
|
||||
return Response.status(Status.BAD_REQUEST)
|
||||
.entity("receipt credential presentation verification failed")
|
||||
.type(MediaType.TEXT_PLAIN_TYPE)
|
||||
.build();
|
||||
}
|
||||
|
||||
final ReceiptSerial receiptSerial = receiptCredentialPresentation.getReceiptSerial();
|
||||
final Instant receiptExpiration = Instant.ofEpochSecond(receiptCredentialPresentation.getReceiptExpirationTime());
|
||||
final long receiptLevel = receiptCredentialPresentation.getReceiptLevel();
|
||||
final String badgeId = badgesConfiguration.getReceiptLevels().get(receiptLevel);
|
||||
if (badgeId == null) {
|
||||
return Response.serverError()
|
||||
.entity("server does not recognize the requested receipt level")
|
||||
.type(MediaType.TEXT_PLAIN_TYPE)
|
||||
.build();
|
||||
}
|
||||
|
||||
final Account account = accountsManager.getByAccountIdentifier(auth.accountIdentifier())
|
||||
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
|
||||
|
||||
final boolean receiptMatched = redeemedReceiptsManager.put(
|
||||
receiptSerial, receiptExpiration.getEpochSecond(), receiptLevel, auth.accountIdentifier()).join();
|
||||
if (!receiptMatched) {
|
||||
return Response.status(Status.BAD_REQUEST)
|
||||
.entity("receipt serial is already redeemed")
|
||||
.type(MediaType.TEXT_PLAIN_TYPE)
|
||||
.build();
|
||||
}
|
||||
|
||||
accountsManager.update(account, a -> {
|
||||
a.addBadge(clock, new AccountBadge(badgeId, receiptExpiration, request.isVisible()));
|
||||
if (request.isPrimary()) {
|
||||
a.makeBadgePrimaryIfExists(clock, badgeId);
|
||||
}
|
||||
try {
|
||||
serverZkReceiptOperations.verifyReceiptCredentialPresentation(receiptCredentialPresentation);
|
||||
} catch (VerificationFailedException e) {
|
||||
return CompletableFuture.completedFuture(Response.status(Status.BAD_REQUEST)
|
||||
.entity("receipt credential presentation verification failed")
|
||||
.type(MediaType.TEXT_PLAIN_TYPE)
|
||||
.build());
|
||||
}
|
||||
|
||||
final ReceiptSerial receiptSerial = receiptCredentialPresentation.getReceiptSerial();
|
||||
final Instant receiptExpiration = Instant.ofEpochSecond(receiptCredentialPresentation.getReceiptExpirationTime());
|
||||
final long receiptLevel = receiptCredentialPresentation.getReceiptLevel();
|
||||
final String badgeId = badgesConfiguration.getReceiptLevels().get(receiptLevel);
|
||||
if (badgeId == null) {
|
||||
return CompletableFuture.completedFuture(Response.serverError()
|
||||
.entity("server does not recognize the requested receipt level")
|
||||
.type(MediaType.TEXT_PLAIN_TYPE)
|
||||
.build());
|
||||
}
|
||||
|
||||
return accountsManager.getByAccountIdentifierAsync(auth.accountIdentifier())
|
||||
.thenCompose(maybeAccount -> {
|
||||
final Account account = maybeAccount.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
|
||||
|
||||
return redeemedReceiptsManager.put(
|
||||
receiptSerial, receiptExpiration.getEpochSecond(), receiptLevel, auth.accountIdentifier())
|
||||
.thenCompose(receiptMatched -> {
|
||||
if (!receiptMatched) {
|
||||
return CompletableFuture.completedFuture(Response.status(Status.BAD_REQUEST)
|
||||
.entity("receipt serial is already redeemed")
|
||||
.type(MediaType.TEXT_PLAIN_TYPE)
|
||||
.build());
|
||||
}
|
||||
|
||||
return accountsManager.updateAsync(account, a -> {
|
||||
a.addBadge(clock, new AccountBadge(badgeId, receiptExpiration, request.isVisible()));
|
||||
if (request.isPrimary()) {
|
||||
a.makeBadgePrimaryIfExists(clock, badgeId);
|
||||
}
|
||||
})
|
||||
.thenApply(ignored -> Response.ok().build());
|
||||
});
|
||||
});
|
||||
}).thenCompose(Function.identity());
|
||||
});
|
||||
return Response.ok().build();
|
||||
}
|
||||
|
||||
}
|
||||
+154
-134
@@ -52,11 +52,11 @@ import java.util.Map;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
import javax.annotation.Nonnull;
|
||||
import javax.annotation.Nullable;
|
||||
import org.glassfish.jersey.server.ManagedAsync;
|
||||
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialResponse;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupManager;
|
||||
@@ -65,15 +65,18 @@ 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.storage.SubscriptionException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionException;
|
||||
import org.whispersystems.textsecuregcm.storage.SubscriptionManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Subscriptions;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.AppleAppStoreManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.BankMandateTranslator;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.BankTransferType;
|
||||
@@ -85,7 +88,10 @@ import org.whispersystems.textsecuregcm.subscriptions.PaymentMethod;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.ProcessorCustomer;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.StripeManager;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidArgumentsException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidLevelException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentRequiresActionException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptRequestedForOpenPaymentException;
|
||||
import org.whispersystems.textsecuregcm.util.HeaderUtils;
|
||||
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
|
||||
import org.whispersystems.textsecuregcm.util.ua.UnrecognizedUserAgentException;
|
||||
@@ -105,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";
|
||||
@@ -120,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);
|
||||
@@ -131,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() {
|
||||
@@ -203,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())));
|
||||
|
||||
@@ -233,12 +244,14 @@ public class SubscriptionController {
|
||||
@ApiResponse(responseCode = "429", description = "Too many attempts", headers = @Header(
|
||||
name = "Retry-After",
|
||||
description = "If present, a positive integer indicating the number of seconds before a subsequent attempt could succeed"))
|
||||
public CompletableFuture<Response> deleteSubscriber(
|
||||
@ManagedAsync
|
||||
public Response deleteSubscriber(
|
||||
@Auth Optional<AuthenticatedDevice> authenticatedAccount,
|
||||
@PathParam("subscriberId") String subscriberId) throws SubscriptionException {
|
||||
@PathParam("subscriberId") String subscriberId) throws SubscriptionException, RateLimitExceededException {
|
||||
SubscriberCredentials subscriberCredentials =
|
||||
SubscriberCredentials.process(authenticatedAccount, subscriberId, clock);
|
||||
return subscriptionManager.deleteSubscriber(subscriberCredentials).thenApply(unused -> Response.ok().build());
|
||||
subscriptionManager.deleteSubscriber(subscriberCredentials);
|
||||
return Response.ok().build();
|
||||
}
|
||||
|
||||
@PUT
|
||||
@@ -255,15 +268,17 @@ public class SubscriptionController {
|
||||
@ApiResponse(responseCode = "200", description = "The subscriber was successfully created or refreshed")
|
||||
@ApiResponse(responseCode = "403", description = "subscriberId authentication failure OR account authentication is present")
|
||||
@ApiResponse(responseCode = "404", description = "subscriberId is malformed")
|
||||
public CompletableFuture<Response> updateSubscriber(
|
||||
@ManagedAsync
|
||||
public Response updateSubscriber(
|
||||
@Auth Optional<AuthenticatedDevice> authenticatedAccount,
|
||||
@PathParam("subscriberId") String subscriberId) throws SubscriptionException {
|
||||
SubscriberCredentials subscriberCredentials =
|
||||
SubscriberCredentials.process(authenticatedAccount, subscriberId, clock);
|
||||
return subscriptionManager.updateSubscriber(subscriberCredentials).thenApply(record -> Response.ok().build());
|
||||
subscriptionManager.updateSubscriber(subscriberCredentials);
|
||||
return Response.ok().build();
|
||||
}
|
||||
|
||||
record CreatePaymentMethodResponse(String clientSecret, PaymentProvider processor) {
|
||||
public record CreatePaymentMethodResponse(String clientSecret, PaymentProvider processor) {
|
||||
|
||||
}
|
||||
|
||||
@@ -271,7 +286,8 @@ public class SubscriptionController {
|
||||
@Path("/{subscriberId}/create_payment_method")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public CompletableFuture<Response> createPaymentMethod(
|
||||
@ManagedAsync
|
||||
public CreatePaymentMethodResponse createPaymentMethod(
|
||||
@Auth Optional<AuthenticatedDevice> authenticatedAccount,
|
||||
@PathParam("subscriberId") String subscriberId,
|
||||
@QueryParam("type") @DefaultValue("CARD") PaymentMethod paymentMethodType,
|
||||
@@ -290,13 +306,13 @@ public class SubscriptionController {
|
||||
case UNKNOWN -> throw new BadRequestException("Invalid payment method");
|
||||
};
|
||||
|
||||
return subscriptionManager.addPaymentMethodToCustomer(
|
||||
subscriberCredentials,
|
||||
customerAwareSubscriptionPaymentProcessor,
|
||||
getClientPlatform(userAgentString),
|
||||
CustomerAwareSubscriptionPaymentProcessor::createPaymentMethodSetupToken)
|
||||
.thenApply(token ->
|
||||
Response.ok(new CreatePaymentMethodResponse(token, customerAwareSubscriptionPaymentProcessor.getProvider())).build());
|
||||
final String token = subscriptionManager.addPaymentMethodToCustomer(
|
||||
subscriberCredentials,
|
||||
customerAwareSubscriptionPaymentProcessor,
|
||||
getClientPlatform(userAgentString),
|
||||
CustomerAwareSubscriptionPaymentProcessor::createPaymentMethodSetupToken);
|
||||
|
||||
return new CreatePaymentMethodResponse(token, customerAwareSubscriptionPaymentProcessor.getProvider());
|
||||
}
|
||||
|
||||
public record CreatePayPalBillingAgreementRequest(@NotBlank String returnUrl, @NotBlank String cancelUrl) {}
|
||||
@@ -307,7 +323,8 @@ public class SubscriptionController {
|
||||
@Path("/{subscriberId}/create_payment_method/paypal")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public CompletableFuture<Response> createPayPalPaymentMethod(
|
||||
@ManagedAsync
|
||||
public CreatePayPalBillingAgreementResponse createPayPalPaymentMethod(
|
||||
@Auth Optional<AuthenticatedDevice> authenticatedAccount,
|
||||
@PathParam("subscriberId") String subscriberId,
|
||||
@NotNull @Valid CreatePayPalBillingAgreementRequest request,
|
||||
@@ -321,17 +338,16 @@ public class SubscriptionController {
|
||||
.findFirst()
|
||||
.orElse(Locale.US);
|
||||
|
||||
return subscriptionManager.addPaymentMethodToCustomer(
|
||||
final BraintreeManager.PayPalBillingAgreementApprovalDetails billingAgreementApprovalDetails = subscriptionManager.addPaymentMethodToCustomer(
|
||||
subscriberCredentials,
|
||||
braintreeManager,
|
||||
getClientPlatform(userAgentString),
|
||||
(mgr, customerId) ->
|
||||
mgr.createPayPalBillingAgreement(request.returnUrl, request.cancelUrl, locale.toLanguageTag()))
|
||||
.thenApply(billingAgreementApprovalDetails -> Response.ok(
|
||||
new CreatePayPalBillingAgreementResponse(
|
||||
billingAgreementApprovalDetails.approvalUrl(),
|
||||
billingAgreementApprovalDetails.billingAgreementToken()))
|
||||
.build());
|
||||
.join();
|
||||
return new CreatePayPalBillingAgreementResponse(
|
||||
billingAgreementApprovalDetails.approvalUrl(),
|
||||
billingAgreementApprovalDetails.billingAgreementToken());
|
||||
}
|
||||
|
||||
private CustomerAwareSubscriptionPaymentProcessor getCustomerAwareProcessor(PaymentProvider processor) {
|
||||
@@ -346,7 +362,8 @@ public class SubscriptionController {
|
||||
@Path("/{subscriberId}/default_payment_method/{processor}/{paymentMethodToken}")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public CompletableFuture<Response> setDefaultPaymentMethodWithProcessor(
|
||||
@ManagedAsync
|
||||
public Response setDefaultPaymentMethodWithProcessor(
|
||||
@Auth Optional<AuthenticatedDevice> authenticatedAccount,
|
||||
@PathParam("subscriberId") String subscriberId,
|
||||
@PathParam("processor") PaymentProvider processor,
|
||||
@@ -356,7 +373,8 @@ public class SubscriptionController {
|
||||
|
||||
final CustomerAwareSubscriptionPaymentProcessor manager = getCustomerAwareProcessor(processor);
|
||||
|
||||
return setDefaultPaymentMethod(manager, paymentMethodToken, subscriberCredentials);
|
||||
setDefaultPaymentMethod(manager, paymentMethodToken, subscriberCredentials);
|
||||
return Response.ok().build();
|
||||
}
|
||||
|
||||
public record SetSubscriptionLevelSuccessResponse(long level) {
|
||||
@@ -383,7 +401,8 @@ public class SubscriptionController {
|
||||
@Path("/{subscriberId}/level/{level}/{currency}/{idempotencyKey}")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public CompletableFuture<Response> setSubscriptionLevel(
|
||||
@ManagedAsync
|
||||
public SetSubscriptionLevelSuccessResponse setSubscriptionLevel(
|
||||
@Auth Optional<AuthenticatedDevice> authenticatedAccount,
|
||||
@PathParam("subscriberId") String subscriberId,
|
||||
@PathParam("level") long level,
|
||||
@@ -391,42 +410,40 @@ public class SubscriptionController {
|
||||
@PathParam("idempotencyKey") String idempotencyKey) throws SubscriptionException {
|
||||
SubscriberCredentials subscriberCredentials =
|
||||
SubscriberCredentials.process(authenticatedAccount, subscriberId, clock);
|
||||
return subscriptionManager.getSubscriber(subscriberCredentials)
|
||||
.thenCompose(record -> {
|
||||
final ProcessorCustomer processorCustomer = record.getProcessorCustomer()
|
||||
.orElseThrow(() ->
|
||||
// a missing customer ID indicates the client made requests out of order,
|
||||
// and needs to call create_payment_method to create a customer for the given payment method
|
||||
new ClientErrorException(Status.CONFLICT));
|
||||
try {
|
||||
final Subscriptions.Record record = subscriptionManager.getSubscriber(subscriberCredentials);
|
||||
final ProcessorCustomer processorCustomer = record.getProcessorCustomer()
|
||||
.orElseThrow(() ->
|
||||
// a missing customer ID indicates the client made requests out of order,
|
||||
// and needs to call create_payment_method to create a customer for the given payment method
|
||||
new ClientErrorException(Status.CONFLICT));
|
||||
|
||||
final String subscriptionTemplateId = getSubscriptionTemplateId(level, currency,
|
||||
processorCustomer.processor());
|
||||
final String subscriptionTemplateId = getSubscriptionTemplateId(level, currency,
|
||||
processorCustomer.processor());
|
||||
|
||||
final CustomerAwareSubscriptionPaymentProcessor manager = getCustomerAwareProcessor(processorCustomer.processor());
|
||||
return subscriptionManager.updateSubscriptionLevelForCustomer(subscriberCredentials, record, manager, level,
|
||||
currency, idempotencyKey, subscriptionTemplateId, this::subscriptionsAreSameType);
|
||||
})
|
||||
.exceptionally(ExceptionUtils.exceptionallyHandler(SubscriptionException.InvalidLevel.class, e -> {
|
||||
throw new BadRequestException(Response.status(Response.Status.BAD_REQUEST)
|
||||
.entity(new SubscriptionController.SetSubscriptionLevelErrorResponse(List.of(
|
||||
new SubscriptionController.SetSubscriptionLevelErrorResponse.Error(
|
||||
SubscriptionController.SetSubscriptionLevelErrorResponse.Error.Type.UNSUPPORTED_LEVEL,
|
||||
null))))
|
||||
.build());
|
||||
}))
|
||||
.exceptionally(ExceptionUtils.exceptionallyHandler(SubscriptionException.PaymentRequiresAction.class, e -> {
|
||||
throw new BadRequestException(Response.status(Response.Status.BAD_REQUEST)
|
||||
.entity(new SetSubscriptionLevelErrorResponse(List.of(new SetSubscriptionLevelErrorResponse.Error(
|
||||
SetSubscriptionLevelErrorResponse.Error.Type.PAYMENT_REQUIRES_ACTION, null))))
|
||||
.build());
|
||||
}))
|
||||
.exceptionally(ExceptionUtils.exceptionallyHandler(SubscriptionException.InvalidArguments.class, e -> {
|
||||
throw new BadRequestException(Response.status(Response.Status.BAD_REQUEST)
|
||||
.entity(new SetSubscriptionLevelErrorResponse(List.of(new SetSubscriptionLevelErrorResponse.Error(
|
||||
SetSubscriptionLevelErrorResponse.Error.Type.INVALID_ARGUMENTS, e.getMessage()))))
|
||||
.build());
|
||||
}))
|
||||
.thenApply(unused -> Response.ok(new SetSubscriptionLevelSuccessResponse(level)).build());
|
||||
final CustomerAwareSubscriptionPaymentProcessor manager = getCustomerAwareProcessor(
|
||||
processorCustomer.processor());
|
||||
subscriptionManager.updateSubscriptionLevelForCustomer(subscriberCredentials, record, manager, level,
|
||||
currency, idempotencyKey, subscriptionTemplateId, this::subscriptionsAreSameType);
|
||||
return new SetSubscriptionLevelSuccessResponse(level);
|
||||
} catch (SubscriptionInvalidLevelException e) {
|
||||
throw new BadRequestException(Response.status(Response.Status.BAD_REQUEST)
|
||||
.entity(new SubscriptionController.SetSubscriptionLevelErrorResponse(List.of(
|
||||
new SubscriptionController.SetSubscriptionLevelErrorResponse.Error(
|
||||
SubscriptionController.SetSubscriptionLevelErrorResponse.Error.Type.UNSUPPORTED_LEVEL,
|
||||
null))))
|
||||
.build());
|
||||
} catch (SubscriptionPaymentRequiresActionException e) {
|
||||
throw new BadRequestException(Response.status(Response.Status.BAD_REQUEST)
|
||||
.entity(new SetSubscriptionLevelErrorResponse(List.of(new SetSubscriptionLevelErrorResponse.Error(
|
||||
SetSubscriptionLevelErrorResponse.Error.Type.PAYMENT_REQUIRES_ACTION, null))))
|
||||
.build());
|
||||
} catch (SubscriptionInvalidArgumentsException e) {
|
||||
throw new BadRequestException(Response.status(Response.Status.BAD_REQUEST)
|
||||
.entity(new SetSubscriptionLevelErrorResponse(List.of(new SetSubscriptionLevelErrorResponse.Error(
|
||||
SetSubscriptionLevelErrorResponse.Error.Type.INVALID_ARGUMENTS, e.getMessage()))))
|
||||
.build());
|
||||
}
|
||||
}
|
||||
|
||||
public boolean subscriptionsAreSameType(long level1, long level2) {
|
||||
@@ -449,7 +466,7 @@ public class SubscriptionController {
|
||||
4. Obtain a receipt at `POST /v1/subscription/{subscriberId}/receipt_credentials` which can then be used to obtain the
|
||||
entitlement
|
||||
""")
|
||||
@ApiResponse(responseCode = "200", description = "The originalTransactionId was successfully validated")
|
||||
@ApiResponse(responseCode = "200", description = "The originalTransactionId was successfully validated", useReturnTypeSchema = true)
|
||||
@ApiResponse(responseCode = "402", description = "The subscription transaction is incomplete or invalid")
|
||||
@ApiResponse(responseCode = "403", description = "subscriberId authentication failure OR account authentication is present")
|
||||
@ApiResponse(responseCode = "404", description = "No such subscriberId exists or subscriberId is malformed or the specified transaction does not exist")
|
||||
@@ -457,16 +474,16 @@ public class SubscriptionController {
|
||||
@ApiResponse(responseCode = "429", description = "Too many attempts", headers = @Header(
|
||||
name = "Retry-After",
|
||||
description = "If present, a positive integer indicating the number of seconds before a subsequent attempt could succeed"))
|
||||
public CompletableFuture<SetSubscriptionLevelSuccessResponse> setAppStoreSubscription(
|
||||
@ManagedAsync
|
||||
public SetSubscriptionLevelSuccessResponse setAppStoreSubscription(
|
||||
@Auth Optional<AuthenticatedDevice> authenticatedAccount,
|
||||
@PathParam("subscriberId") String subscriberId,
|
||||
@PathParam("originalTransactionId") String originalTransactionId) throws SubscriptionException {
|
||||
@PathParam("originalTransactionId") String originalTransactionId) throws SubscriptionException, RateLimitExceededException {
|
||||
final SubscriberCredentials subscriberCredentials =
|
||||
SubscriberCredentials.process(authenticatedAccount, subscriberId, clock);
|
||||
|
||||
return subscriptionManager
|
||||
.updateAppStoreTransactionId(subscriberCredentials, appleAppStoreManager, originalTransactionId)
|
||||
.thenApply(SetSubscriptionLevelSuccessResponse::new);
|
||||
return new SetSubscriptionLevelSuccessResponse(subscriptionManager
|
||||
.updateAppStoreTransactionId(subscriberCredentials, appleAppStoreManager, originalTransactionId));
|
||||
}
|
||||
|
||||
|
||||
@@ -493,7 +510,7 @@ public class SubscriptionController {
|
||||
method. A different playbilling purchaseToken can be posted to the same subscriberId, in this case the subscription
|
||||
associated with the old purchaseToken will be cancelled.
|
||||
""")
|
||||
@ApiResponse(responseCode = "200", description = "The purchaseToken was validated and acknowledged")
|
||||
@ApiResponse(responseCode = "200", description = "The purchaseToken was validated and acknowledged", useReturnTypeSchema = true)
|
||||
@ApiResponse(responseCode = "402", description = "The purchaseToken payment is incomplete or invalid")
|
||||
@ApiResponse(responseCode = "403", description = "subscriberId authentication failure OR account authentication is present")
|
||||
@ApiResponse(responseCode = "404", description = "No such subscriberId exists or subscriberId is malformed or the purchaseToken does not exist")
|
||||
@@ -501,16 +518,16 @@ public class SubscriptionController {
|
||||
@ApiResponse(responseCode = "429", description = "Too many attempts", headers = @Header(
|
||||
name = "Retry-After",
|
||||
description = "If present, a positive integer indicating the number of seconds before a subsequent attempt could succeed"))
|
||||
public CompletableFuture<SetSubscriptionLevelSuccessResponse> setPlayStoreSubscription(
|
||||
@ManagedAsync
|
||||
public SetSubscriptionLevelSuccessResponse setPlayStoreSubscription(
|
||||
@Auth Optional<AuthenticatedDevice> authenticatedAccount,
|
||||
@PathParam("subscriberId") String subscriberId,
|
||||
@PathParam("purchaseToken") String purchaseToken) throws SubscriptionException {
|
||||
@PathParam("purchaseToken") String purchaseToken) throws SubscriptionException, RateLimitExceededException {
|
||||
final SubscriberCredentials subscriberCredentials =
|
||||
SubscriberCredentials.process(authenticatedAccount, subscriberId, clock);
|
||||
|
||||
return subscriptionManager
|
||||
.updatePlayBillingPurchaseToken(subscriberCredentials, googlePlayBillingManager, purchaseToken)
|
||||
.thenApply(SetSubscriptionLevelSuccessResponse::new);
|
||||
return new SetSubscriptionLevelSuccessResponse(subscriptionManager
|
||||
.updatePlayBillingPurchaseToken(subscriberCredentials, googlePlayBillingManager, purchaseToken));
|
||||
}
|
||||
|
||||
@Schema(description = """
|
||||
@@ -572,24 +589,21 @@ public class SubscriptionController {
|
||||
description = """
|
||||
Returns all configuration for badges, donation subscriptions, backup subscriptions, and one-time donation (
|
||||
"boost" and "gift") minimum and suggested amounts.""")
|
||||
@ApiResponse(responseCode = "200", content = @Content(schema = @Schema(implementation = GetSubscriptionConfigurationResponse.class)))
|
||||
public CompletableFuture<Response> getConfiguration(@Context ContainerRequestContext containerRequestContext) {
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
List<Locale> acceptableLanguages = HeaderUtils.getAcceptableLanguagesForRequest(containerRequestContext);
|
||||
return Response.ok(buildGetSubscriptionConfigurationResponse(acceptableLanguages)).build();
|
||||
});
|
||||
@ApiResponse(responseCode = "200", useReturnTypeSchema = true)
|
||||
@ManagedAsync
|
||||
public GetSubscriptionConfigurationResponse getConfiguration(@Context ContainerRequestContext containerRequestContext) {
|
||||
List<Locale> acceptableLanguages = HeaderUtils.getAcceptableLanguagesForRequest(containerRequestContext);
|
||||
return buildGetSubscriptionConfigurationResponse(acceptableLanguages);
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/bank_mandate/{bankTransferType}")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public CompletableFuture<Response> getBankMandate(final @Context ContainerRequestContext containerRequestContext,
|
||||
@ManagedAsync
|
||||
public GetBankMandateResponse getBankMandate(final @Context ContainerRequestContext containerRequestContext,
|
||||
final @PathParam("bankTransferType") BankTransferType bankTransferType) {
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
List<Locale> acceptableLanguages = HeaderUtils.getAcceptableLanguagesForRequest(containerRequestContext);
|
||||
return Response.ok(new GetBankMandateResponse(
|
||||
bankMandateTranslator.translate(acceptableLanguages, bankTransferType))).build();
|
||||
});
|
||||
List<Locale> acceptableLanguages = HeaderUtils.getAcceptableLanguagesForRequest(containerRequestContext);
|
||||
return new GetBankMandateResponse(bankMandateTranslator.translate(acceptableLanguages, bankTransferType));
|
||||
}
|
||||
|
||||
public record GetBankMandateResponse(String mandate) {}
|
||||
@@ -652,19 +666,20 @@ public class SubscriptionController {
|
||||
to Stripe's. Since we don’t support trials or unpaid subscriptions, the associated statuses will never be returned
|
||||
by the API.
|
||||
""")
|
||||
@ApiResponse(responseCode = "200", description = "The subscriberId exists", content = @Content(schema = @Schema(implementation = GetSubscriptionInformationResponse.class)))
|
||||
@ApiResponse(responseCode = "200", description = "The subscriberId exists", useReturnTypeSchema = true)
|
||||
@ApiResponse(responseCode = "403", description = "subscriberId authentication failure OR account authentication is present")
|
||||
@ApiResponse(responseCode = "404", description = "No such subscriberId exists or subscriberId is malformed")
|
||||
@ApiResponse(responseCode = "429", description = "Too many attempts", headers = @Header(
|
||||
name = "Retry-After",
|
||||
description = "If present, a positive integer indicating the number of seconds before a subsequent attempt could succeed"))
|
||||
public CompletableFuture<Response> getSubscriptionInformation(
|
||||
@ManagedAsync
|
||||
public GetSubscriptionInformationResponse getSubscriptionInformation(
|
||||
@Auth Optional<AuthenticatedDevice> authenticatedAccount,
|
||||
@PathParam("subscriberId") String subscriberId) throws SubscriptionException {
|
||||
@PathParam("subscriberId") String subscriberId) throws SubscriptionException, RateLimitExceededException {
|
||||
SubscriberCredentials subscriberCredentials =
|
||||
SubscriberCredentials.process(authenticatedAccount, subscriberId, clock);
|
||||
return subscriptionManager.getSubscriptionInformation(subscriberCredentials).thenApply(maybeInfo -> maybeInfo
|
||||
.map(subscriptionInformation -> Response.ok(
|
||||
return subscriptionManager.getSubscriptionInformation( subscriberCredentials)
|
||||
.map(subscriptionInformation ->
|
||||
new GetSubscriptionInformationResponse(
|
||||
new GetSubscriptionInformationResponse.Subscription(
|
||||
subscriptionInformation.level(),
|
||||
@@ -679,8 +694,8 @@ public class SubscriptionController {
|
||||
subscriptionInformation.paymentMethod(),
|
||||
subscriptionInformation.paymentProcessing()),
|
||||
subscriptionInformation.chargeFailure()
|
||||
)).build())
|
||||
.orElseGet(() -> Response.ok(new GetSubscriptionInformationResponse(null, null)).build()));
|
||||
))
|
||||
.orElseGet(() -> new GetSubscriptionInformationResponse(null, null));
|
||||
}
|
||||
|
||||
public record GetReceiptCredentialsRequest(
|
||||
@@ -717,7 +732,7 @@ public class SubscriptionController {
|
||||
|
||||
Clients MUST validate that the generated receipt credential's level and expiration matches their expectations.
|
||||
""")
|
||||
@ApiResponse(responseCode = "200", description = "Successfully created receipt", content = @Content(schema = @Schema(implementation = GetReceiptCredentialsResponse.class)))
|
||||
@ApiResponse(responseCode = "200", description = "Successfully created receipt", useReturnTypeSchema = true)
|
||||
@ApiResponse(responseCode = "204", description = "No invoice has been issued for this subscription OR invoice is in 'open' state")
|
||||
@ApiResponse(responseCode = "400", description = "Bad ReceiptCredentialRequest")
|
||||
@ApiResponse(responseCode = "402", description = "Invoice is in any state other than 'open' or 'paid'. May include chargeFailure details in body.",
|
||||
@@ -741,63 +756,68 @@ public class SubscriptionController {
|
||||
@ApiResponse(responseCode = "429", description = "Too many attempts", headers = @Header(
|
||||
name = "Retry-After",
|
||||
description = "If present, a positive integer indicating the number of seconds before a subsequent attempt could succeed"))
|
||||
public CompletableFuture<Response> createSubscriptionReceiptCredentials(
|
||||
@ManagedAsync
|
||||
public Response createSubscriptionReceiptCredentials(
|
||||
@Auth Optional<AuthenticatedDevice> authenticatedAccount,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
|
||||
@PathParam("subscriberId") String subscriberId,
|
||||
@NotNull @Valid GetReceiptCredentialsRequest request) throws SubscriptionException {
|
||||
@NotNull @Valid GetReceiptCredentialsRequest request) throws SubscriptionException, RateLimitExceededException {
|
||||
SubscriberCredentials subscriberCredentials = SubscriberCredentials.process(authenticatedAccount, subscriberId, clock);
|
||||
return subscriptionManager.createReceiptCredentials(subscriberCredentials, request, this::receiptExpirationWithGracePeriod)
|
||||
.thenApply(receiptCredential -> {
|
||||
final ReceiptCredentialResponse receiptCredentialResponse = receiptCredential.receiptCredentialResponse();
|
||||
final CustomerAwareSubscriptionPaymentProcessor.ReceiptItem receipt = receiptCredential.receiptItem();
|
||||
Metrics.counter(RECEIPT_ISSUED_COUNTER_NAME,
|
||||
Tags.of(
|
||||
Tag.of(PROCESSOR_TAG_NAME, receiptCredential.paymentProvider().toString()),
|
||||
Tag.of(TYPE_TAG_NAME, "subscription"),
|
||||
Tag.of(SUBSCRIPTION_TYPE_TAG_NAME,
|
||||
subscriptionConfiguration.getSubscriptionLevel(receipt.level()).type().name()
|
||||
.toLowerCase(Locale.ROOT)),
|
||||
UserAgentTagUtil.getPlatformTag(userAgent)))
|
||||
.increment();
|
||||
return Response.ok(new GetReceiptCredentialsResponse(receiptCredentialResponse.serialize())).build();
|
||||
})
|
||||
.exceptionally(ExceptionUtils.exceptionallyHandler(
|
||||
SubscriptionException.ReceiptRequestedForOpenPayment.class,
|
||||
e -> Response.noContent().build()));
|
||||
try {
|
||||
final SubscriptionManager.ReceiptResult receiptCredential = subscriptionManager.createReceiptCredentials(
|
||||
subscriberCredentials, request, this::receiptExpirationWithGracePeriod);
|
||||
|
||||
final ReceiptCredentialResponse receiptCredentialResponse = receiptCredential.receiptCredentialResponse();
|
||||
final CustomerAwareSubscriptionPaymentProcessor.ReceiptItem receipt = receiptCredential.receiptItem();
|
||||
Metrics.counter(RECEIPT_ISSUED_COUNTER_NAME,
|
||||
Tags.of(
|
||||
Tag.of(PROCESSOR_TAG_NAME, receiptCredential.paymentProvider().toString()),
|
||||
Tag.of(TYPE_TAG_NAME, "subscription"),
|
||||
Tag.of(SUBSCRIPTION_TYPE_TAG_NAME,
|
||||
subscriptionConfiguration.getSubscriptionLevel(receipt.level()).type().name()
|
||||
.toLowerCase(Locale.ROOT)),
|
||||
UserAgentTagUtil.getPlatformTag(userAgent)))
|
||||
.increment();
|
||||
return Response.ok(new GetReceiptCredentialsResponse(receiptCredentialResponse.serialize())).build();
|
||||
} catch (SubscriptionReceiptRequestedForOpenPaymentException e) {
|
||||
return Response.noContent().build();
|
||||
}
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/{subscriberId}/default_payment_method_for_ideal/{setupIntentId}")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public CompletableFuture<Response> setDefaultPaymentMethodForIdeal(
|
||||
@ManagedAsync
|
||||
public Response setDefaultPaymentMethodForIdeal(
|
||||
@Auth Optional<AuthenticatedDevice> authenticatedAccount,
|
||||
@PathParam("subscriberId") String subscriberId,
|
||||
@PathParam("setupIntentId") @NotEmpty String setupIntentId) throws SubscriptionException {
|
||||
SubscriberCredentials subscriberCredentials =
|
||||
SubscriberCredentials.process(authenticatedAccount, subscriberId, clock);
|
||||
|
||||
return stripeManager.getGeneratedSepaIdFromSetupIntent(setupIntentId)
|
||||
.thenCompose(generatedSepaId -> setDefaultPaymentMethod(stripeManager, generatedSepaId, subscriberCredentials));
|
||||
final String generatedSepaId = stripeManager.getGeneratedSepaIdFromSetupIntent(setupIntentId).join();
|
||||
setDefaultPaymentMethod(stripeManager, generatedSepaId, subscriberCredentials);
|
||||
return Response.ok().build();
|
||||
}
|
||||
|
||||
private CompletableFuture<Response> setDefaultPaymentMethod(final CustomerAwareSubscriptionPaymentProcessor manager,
|
||||
private void setDefaultPaymentMethod(final CustomerAwareSubscriptionPaymentProcessor manager,
|
||||
final String paymentMethodId,
|
||||
final SubscriberCredentials requestData) {
|
||||
return subscriptionManager.getSubscriber(requestData)
|
||||
.thenCompose(record -> record.getProcessorCustomer()
|
||||
.map(processorCustomer -> manager.setDefaultPaymentMethodForCustomer(processorCustomer.customerId(),
|
||||
paymentMethodId, record.subscriptionId))
|
||||
.orElseThrow(() ->
|
||||
// a missing customer ID indicates the client made requests out of order,
|
||||
// and needs to call create_payment_method to create a customer for the given payment method
|
||||
new ClientErrorException(Status.CONFLICT)))
|
||||
.exceptionally(ExceptionUtils.exceptionallyHandler(SubscriptionException.InvalidArguments.class, e -> {
|
||||
// Here, invalid arguments must mean that the client has made requests out of order, and needs to finish
|
||||
// setting up the paymentMethod first
|
||||
throw new ClientErrorException(Status.CONFLICT);
|
||||
}))
|
||||
.thenApply(customer -> Response.ok().build());
|
||||
final SubscriberCredentials requestData) throws SubscriptionException {
|
||||
try {
|
||||
final Subscriptions.Record record = subscriptionManager.getSubscriber(requestData);
|
||||
|
||||
final ProcessorCustomer processorCustomer = record.getProcessorCustomer()
|
||||
// a missing customer ID indicates the client made requests out of order,
|
||||
// and needs to call create_payment_method to create a customer for the given payment method
|
||||
.orElseThrow(() ->new ClientErrorException(Status.CONFLICT));
|
||||
|
||||
manager
|
||||
.setDefaultPaymentMethodForCustomer(processorCustomer.customerId(), paymentMethodId, record.subscriptionId);
|
||||
} catch (SubscriptionInvalidArgumentsException e) {
|
||||
// Here, invalid arguments must mean that the client has made requests out of order, and needs to finish
|
||||
// setting up the paymentMethod first
|
||||
throw new ClientErrorException(Status.CONFLICT);
|
||||
}
|
||||
}
|
||||
|
||||
private Instant receiptExpirationWithGracePeriod(CustomerAwareSubscriptionPaymentProcessor.ReceiptItem receiptItem) {
|
||||
|
||||
+5
-1
@@ -51,10 +51,14 @@ public record IncomingMessage(int type,
|
||||
.setClientTimestamp(timestamp)
|
||||
.setServerTimestamp(clock.millis())
|
||||
.setDestinationServiceId(destinationIdentifier.toServiceIdentifierString())
|
||||
.setStory(story)
|
||||
.setEphemeral(ephemeral)
|
||||
.setUrgent(urgent);
|
||||
|
||||
if (story) {
|
||||
// Avoid sending this field if it's false.
|
||||
envelopeBuilder.setStory(true);
|
||||
}
|
||||
|
||||
if (sourceServiceIdentifier != null && sourceDeviceId != null) {
|
||||
envelopeBuilder
|
||||
.setSourceServiceId(sourceServiceIdentifier.toServiceIdentifierString())
|
||||
|
||||
+5
-1
@@ -46,9 +46,13 @@ public record OutgoingMessageEntity(UUID guid,
|
||||
.setServerTimestamp(serverTimestamp())
|
||||
.setDestinationServiceId(destinationUuid().toServiceIdentifierString())
|
||||
.setServerGuid(guid().toString())
|
||||
.setStory(story)
|
||||
.setUrgent(urgent);
|
||||
|
||||
if (story) {
|
||||
// Avoid sending this field if it's false.
|
||||
builder.setStory(true);
|
||||
}
|
||||
|
||||
if (sourceUuid() != null) {
|
||||
builder.setSourceServiceId(sourceUuid().toServiceIdentifierString());
|
||||
builder.setSourceDevice(sourceDevice());
|
||||
|
||||
+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 {
|
||||
|
||||
+13
-11
@@ -6,12 +6,11 @@ package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import io.grpc.Status;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import org.signal.chat.backup.GetBackupAuthCredentialsRequest;
|
||||
import org.signal.chat.backup.GetBackupAuthCredentialsResponse;
|
||||
import org.signal.chat.backup.ReactorBackupsGrpc;
|
||||
@@ -24,10 +23,10 @@ import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.backups.BackupAuthCredentialRequest;
|
||||
import org.signal.libsignal.zkgroup.backups.BackupCredentialType;
|
||||
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialPresentation;
|
||||
import org.whispersystems.textsecuregcm.auth.RedemptionRange;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupAuthManager;
|
||||
import org.whispersystems.textsecuregcm.controllers.ArchiveController;
|
||||
import org.whispersystems.textsecuregcm.metrics.BackupMetrics;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
@@ -35,8 +34,6 @@ import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
public class BackupsGrpcService extends ReactorBackupsGrpc.BackupsImplBase {
|
||||
|
||||
private final AccountsManager accountManager;
|
||||
@@ -85,14 +82,20 @@ public class BackupsGrpcService extends ReactorBackupsGrpc.BackupsImplBase {
|
||||
@Override
|
||||
public Mono<GetBackupAuthCredentialsResponse> getBackupAuthCredentials(GetBackupAuthCredentialsRequest request) {
|
||||
final Tag platformTag = UserAgentTagUtil.getPlatformTag(RequestAttributesUtil.getUserAgent().orElse(null));
|
||||
final RedemptionRange redemptionRange;
|
||||
try {
|
||||
redemptionRange = RedemptionRange.inclusive(Clock.systemUTC(),
|
||||
Instant.ofEpochSecond(request.getRedemptionStart()),
|
||||
Instant.ofEpochSecond(request.getRedemptionStop()));
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw Status.INVALID_ARGUMENT.withDescription(e.getMessage()).asRuntimeException();
|
||||
}
|
||||
return authenticatedAccount().flatMap(account -> {
|
||||
|
||||
final Mono<List<BackupAuthManager.Credential>> messageCredentials = Mono.fromCompletionStage(() ->
|
||||
backupAuthManager.getBackupAuthCredentials(
|
||||
account,
|
||||
BackupCredentialType.MESSAGES,
|
||||
Instant.ofEpochSecond(request.getRedemptionStart()),
|
||||
Instant.ofEpochSecond(request.getRedemptionStop())))
|
||||
redemptionRange))
|
||||
.doOnSuccess(credentials ->
|
||||
backupMetrics.updateGetCredentialCounter(platformTag, BackupCredentialType.MESSAGES, credentials.size()));
|
||||
|
||||
@@ -100,8 +103,7 @@ public class BackupsGrpcService extends ReactorBackupsGrpc.BackupsImplBase {
|
||||
backupAuthManager.getBackupAuthCredentials(
|
||||
account,
|
||||
BackupCredentialType.MEDIA,
|
||||
Instant.ofEpochSecond(request.getRedemptionStart()),
|
||||
Instant.ofEpochSecond(request.getRedemptionStop())))
|
||||
redemptionRange))
|
||||
.doOnSuccess(credentials ->
|
||||
backupMetrics.updateGetCredentialCounter(platformTag, BackupCredentialType.MEDIA, credentials.size()));
|
||||
|
||||
|
||||
+5
-1
@@ -168,9 +168,13 @@ public class MessagesAnonymousGrpcService extends SimpleMessagesAnonymousGrpc.Me
|
||||
.setDestinationServiceId(destinationServiceIdentifier.toServiceIdentifierString())
|
||||
.setEphemeral(ephemeral)
|
||||
.setUrgent(urgent)
|
||||
.setStory(story)
|
||||
.setContent(entry.getValue().getPayload());
|
||||
|
||||
if (story) {
|
||||
// Avoid sending this field if it's false.
|
||||
envelopeBuilder.setStory(true);
|
||||
}
|
||||
|
||||
spamCheckResult.token().ifPresent(reportSpamToken ->
|
||||
envelopeBuilder.setReportSpamToken(ByteString.copyFrom(reportSpamToken)));
|
||||
|
||||
|
||||
@@ -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);
|
||||
|
||||
+17
-9
@@ -12,8 +12,16 @@ import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import jakarta.ws.rs.ext.ExceptionMapper;
|
||||
import java.util.Map;
|
||||
import org.whispersystems.textsecuregcm.storage.SubscriptionException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionChargeFailurePaymentRequiredException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.ChargeFailure;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionForbiddenException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidAmountException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidArgumentsException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionNotFoundException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentRequiredException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorConflictException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorException;
|
||||
|
||||
public class SubscriptionExceptionMapper implements ExceptionMapper<SubscriptionException> {
|
||||
@VisibleForTesting
|
||||
@@ -25,20 +33,20 @@ public class SubscriptionExceptionMapper implements ExceptionMapper<Subscription
|
||||
public Response toResponse(final SubscriptionException exception) {
|
||||
|
||||
// Some exceptions have specific error body formats
|
||||
if (exception instanceof SubscriptionException.InvalidAmount e) {
|
||||
if (exception instanceof SubscriptionInvalidAmountException e) {
|
||||
return Response
|
||||
.status(Response.Status.BAD_REQUEST)
|
||||
.entity(Map.of("error", e.getErrorCode()))
|
||||
.type(MediaType.APPLICATION_JSON_TYPE)
|
||||
.build();
|
||||
}
|
||||
if (exception instanceof SubscriptionException.ProcessorException e) {
|
||||
if (exception instanceof SubscriptionProcessorException e) {
|
||||
return Response.status(PROCESSOR_ERROR_STATUS_CODE)
|
||||
.entity(new ChargeFailureResponse(e.getProcessor().name(), e.getChargeFailure()))
|
||||
.type(MediaType.APPLICATION_JSON_TYPE)
|
||||
.build();
|
||||
}
|
||||
if (exception instanceof SubscriptionException.ChargeFailurePaymentRequired e) {
|
||||
if (exception instanceof SubscriptionChargeFailurePaymentRequiredException e) {
|
||||
return Response
|
||||
.status(Response.Status.PAYMENT_REQUIRED)
|
||||
.entity(new ChargeFailureResponse(e.getProcessor().name(), e.getChargeFailure()))
|
||||
@@ -48,11 +56,11 @@ public class SubscriptionExceptionMapper implements ExceptionMapper<Subscription
|
||||
|
||||
// Otherwise, we'll return a generic error message WebApplicationException, with a detailed error if one is provided
|
||||
final Response.Status status = (switch (exception) {
|
||||
case SubscriptionException.NotFound e -> Response.Status.NOT_FOUND;
|
||||
case SubscriptionException.Forbidden e -> Response.Status.FORBIDDEN;
|
||||
case SubscriptionException.InvalidArguments e -> Response.Status.BAD_REQUEST;
|
||||
case SubscriptionException.ProcessorConflict e -> Response.Status.CONFLICT;
|
||||
case SubscriptionException.PaymentRequired e -> Response.Status.PAYMENT_REQUIRED;
|
||||
case SubscriptionNotFoundException e -> Response.Status.NOT_FOUND;
|
||||
case SubscriptionForbiddenException e -> Response.Status.FORBIDDEN;
|
||||
case SubscriptionInvalidArgumentsException e -> Response.Status.BAD_REQUEST;
|
||||
case SubscriptionProcessorConflictException e -> Response.Status.CONFLICT;
|
||||
case SubscriptionPaymentRequiredException e -> Response.Status.PAYMENT_REQUIRED;
|
||||
default -> Response.Status.INTERNAL_SERVER_ERROR;
|
||||
});
|
||||
|
||||
|
||||
+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);
|
||||
}
|
||||
}
|
||||
+6
-3
@@ -69,14 +69,17 @@ public class FaultTolerantRedisClient {
|
||||
redisUri.setLibraryVersion(null);
|
||||
|
||||
this.redisClient = RedisClient.create(clientResourcesBuilder.build(), redisUri);
|
||||
this.redisClient.setOptions(ClientOptions.builder()
|
||||
final ClientOptions.Builder clientOptionsBuilder = ClientOptions.builder()
|
||||
.disconnectedBehavior(ClientOptions.DisconnectedBehavior.REJECT_COMMANDS)
|
||||
// for asynchronous commands
|
||||
.timeoutOptions(TimeoutOptions.builder()
|
||||
.fixedTimeout(commandTimeout)
|
||||
.build())
|
||||
.publishOnScheduler(true)
|
||||
.build());
|
||||
.publishOnScheduler(true);
|
||||
|
||||
NettyUtil.setSocketTimeoutsIfApplicable(clientOptionsBuilder);
|
||||
|
||||
this.redisClient.setOptions(clientOptionsBuilder.build());
|
||||
|
||||
this.stringConnection = redisClient.connect();
|
||||
this.binaryConnection = redisClient.connect(ByteArrayCodec.INSTANCE);
|
||||
|
||||
+7
-3
@@ -89,7 +89,8 @@ public class FaultTolerantRedisClusterClient {
|
||||
clientResourcesBuilder.nettyCustomizer(lettuceShardCircuitBreaker).
|
||||
build(),
|
||||
redisUris);
|
||||
this.clusterClient.setOptions(ClusterClientOptions.builder()
|
||||
|
||||
final ClusterClientOptions.Builder clusterClientOptionsBuilder = ClusterClientOptions.builder()
|
||||
.disconnectedBehavior(ClientOptions.DisconnectedBehavior.REJECT_COMMANDS)
|
||||
.validateClusterNodeMembership(false)
|
||||
.topologyRefreshOptions(ClusterTopologyRefreshOptions.builder()
|
||||
@@ -99,8 +100,11 @@ public class FaultTolerantRedisClusterClient {
|
||||
.timeoutOptions(TimeoutOptions.builder()
|
||||
.fixedTimeout(commandTimeout)
|
||||
.build())
|
||||
.publishOnScheduler(true)
|
||||
.build());
|
||||
.publishOnScheduler(true);
|
||||
|
||||
NettyUtil.setSocketTimeoutsIfApplicable(clusterClientOptionsBuilder);
|
||||
|
||||
this.clusterClient.setOptions(clusterClientOptionsBuilder.build());
|
||||
|
||||
this.stringConnection = clusterClient.connect();
|
||||
this.binaryConnection = clusterClient.connect(ByteArrayCodec.INSTANCE);
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.redis;
|
||||
|
||||
import io.lettuce.core.ClientOptions;
|
||||
import io.lettuce.core.SocketOptions;
|
||||
import io.lettuce.core.resource.EpollProvider;
|
||||
import java.time.Duration;
|
||||
|
||||
public class NettyUtil {
|
||||
static final Duration TCP_KEEPALIVE_IDLE = Duration.ofSeconds(30);
|
||||
static final Duration TCP_KEEPALIVE_INTERVAL = Duration.ofSeconds(30);
|
||||
static final Duration TCP_USER_TIMEOUT = Duration.ofSeconds(30);
|
||||
|
||||
static void setSocketTimeoutsIfApplicable(final ClientOptions.Builder clientOptionsBuilder) {
|
||||
if (EpollProvider.isAvailable()) {
|
||||
// These socket options are only available with epoll native transport.
|
||||
clientOptionsBuilder.socketOptions(SocketOptions.builder()
|
||||
.keepAlive(SocketOptions.KeepAliveOptions.builder()
|
||||
.interval(TCP_KEEPALIVE_INTERVAL)
|
||||
.idle(TCP_KEEPALIVE_IDLE)
|
||||
.enable()
|
||||
.build())
|
||||
.tcpUserTimeout(SocketOptions.TcpUserTimeoutOptions.builder()
|
||||
.enable()
|
||||
.tcpUserTimeout(TCP_USER_TIMEOUT)
|
||||
.build())
|
||||
.build());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -322,6 +322,9 @@ public class Accounts {
|
||||
existingAccount.getBackupCredentialRequest(BackupCredentialType.MESSAGES).orElse(null),
|
||||
existingAccount.getBackupCredentialRequest(BackupCredentialType.MEDIA).orElse(null));
|
||||
|
||||
// Carry over the existing backup voucher to the new account
|
||||
accountToCreate.setBackupVoucher(existingAccount.getBackupVoucher());
|
||||
|
||||
final List<TransactWriteItem> writeItems = new ArrayList<>();
|
||||
|
||||
// If we're reclaiming an account that already has a username, we'd like to give the re-registering client
|
||||
|
||||
+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) {
|
||||
|
||||
@@ -145,15 +145,20 @@ public class MessagesManager {
|
||||
|
||||
return insertSharedMultiRecipientMessagePayload(multiRecipientMessage)
|
||||
.thenCompose(sharedMrmKey -> {
|
||||
final Envelope prototypeMessage = Envelope.newBuilder()
|
||||
final Envelope.Builder envelopeBuilder = Envelope.newBuilder()
|
||||
.setType(Envelope.Type.UNIDENTIFIED_SENDER)
|
||||
.setClientTimestamp(clientTimestamp == 0 ? serverTimestamp : clientTimestamp)
|
||||
.setServerTimestamp(serverTimestamp)
|
||||
.setStory(isStory)
|
||||
.setEphemeral(isEphemeral)
|
||||
.setUrgent(isUrgent)
|
||||
.setSharedMrmKey(ByteString.copyFrom(sharedMrmKey))
|
||||
.build();
|
||||
.setSharedMrmKey(ByteString.copyFrom(sharedMrmKey));
|
||||
|
||||
if (isStory) {
|
||||
// Avoid sending this field if it's false.
|
||||
envelopeBuilder.setStory(true);
|
||||
}
|
||||
|
||||
final Envelope prototypeMessage = envelopeBuilder.build();
|
||||
|
||||
final Map<Account, Map<Byte, Boolean>> clientPresenceByAccountAndDevice = new ConcurrentHashMap<>();
|
||||
|
||||
|
||||
+8
-5
@@ -15,6 +15,9 @@ import javax.annotation.Nonnull;
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionForbiddenException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionNotFoundException;
|
||||
|
||||
public record SubscriberCredentials(@Nonnull byte[] subscriberBytes,
|
||||
@Nonnull byte[] subscriberUser,
|
||||
@@ -25,10 +28,10 @@ public record SubscriberCredentials(@Nonnull byte[] subscriberBytes,
|
||||
public static SubscriberCredentials process(
|
||||
Optional<AuthenticatedDevice> authenticatedAccount,
|
||||
String subscriberId,
|
||||
Clock clock) throws SubscriptionException{
|
||||
Clock clock) throws SubscriptionException {
|
||||
Instant now = clock.instant();
|
||||
if (authenticatedAccount.isPresent()) {
|
||||
throw new SubscriptionException.Forbidden("must not use authenticated connection for subscriber operations");
|
||||
throw new SubscriptionForbiddenException("must not use authenticated connection for subscriber operations");
|
||||
}
|
||||
byte[] subscriberBytes = convertSubscriberIdStringToBytes(subscriberId);
|
||||
byte[] subscriberUser = getUser(subscriberBytes);
|
||||
@@ -37,15 +40,15 @@ public record SubscriberCredentials(@Nonnull byte[] subscriberBytes,
|
||||
return new SubscriberCredentials(subscriberBytes, subscriberUser, subscriberKey, hmac, now);
|
||||
}
|
||||
|
||||
private static byte[] convertSubscriberIdStringToBytes(String subscriberId) throws SubscriptionException.NotFound {
|
||||
private static byte[] convertSubscriberIdStringToBytes(String subscriberId) throws SubscriptionNotFoundException {
|
||||
try {
|
||||
byte[] bytes = Base64.getUrlDecoder().decode(subscriberId);
|
||||
if (bytes.length != 32) {
|
||||
throw new SubscriptionException.NotFound();
|
||||
throw new SubscriptionNotFoundException();
|
||||
}
|
||||
return bytes;
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw new SubscriptionException.NotFound(e);
|
||||
throw new SubscriptionNotFoundException(e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
-164
@@ -1,164 +0,0 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import java.util.Optional;
|
||||
import javax.annotation.Nullable;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.ChargeFailure;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
|
||||
|
||||
public class SubscriptionException extends Exception {
|
||||
|
||||
private @Nullable String errorDetail;
|
||||
|
||||
public SubscriptionException(Exception cause) {
|
||||
this(cause, null);
|
||||
}
|
||||
|
||||
SubscriptionException(Exception cause, String errorDetail) {
|
||||
super(cause);
|
||||
this.errorDetail = errorDetail;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return An error message suitable to include in a client response
|
||||
*/
|
||||
public Optional<String> errorDetail() {
|
||||
return Optional.ofNullable(errorDetail);
|
||||
}
|
||||
|
||||
public static class NotFound extends SubscriptionException {
|
||||
|
||||
public NotFound() {
|
||||
super(null);
|
||||
}
|
||||
|
||||
public NotFound(Exception cause) {
|
||||
super(cause);
|
||||
}
|
||||
}
|
||||
|
||||
public static class Forbidden extends SubscriptionException {
|
||||
|
||||
public Forbidden(final String message) {
|
||||
super(null, message);
|
||||
}
|
||||
}
|
||||
|
||||
public static class InvalidArguments extends SubscriptionException {
|
||||
|
||||
public InvalidArguments(final String message, final Exception cause) {
|
||||
super(cause, message);
|
||||
}
|
||||
|
||||
public InvalidArguments(final String message) {
|
||||
this(message, null);
|
||||
}
|
||||
}
|
||||
|
||||
public static class InvalidLevel extends InvalidArguments {
|
||||
|
||||
public InvalidLevel() {
|
||||
super(null, null);
|
||||
}
|
||||
}
|
||||
|
||||
public static class InvalidAmount extends InvalidArguments {
|
||||
private String errorCode;
|
||||
|
||||
public InvalidAmount(String errorCode) {
|
||||
super(null, null);
|
||||
this.errorCode = errorCode;
|
||||
}
|
||||
|
||||
public String getErrorCode() {
|
||||
return errorCode;
|
||||
}
|
||||
}
|
||||
|
||||
public static class PaymentRequiresAction extends InvalidArguments {
|
||||
|
||||
public PaymentRequiresAction(String message) {
|
||||
super(message, null);
|
||||
}
|
||||
|
||||
public PaymentRequiresAction() {
|
||||
super(null, null);
|
||||
}
|
||||
}
|
||||
|
||||
public static class PaymentRequired extends SubscriptionException {
|
||||
|
||||
public PaymentRequired() {
|
||||
super(null, null);
|
||||
}
|
||||
|
||||
public PaymentRequired(String message) {
|
||||
super(null, message);
|
||||
}
|
||||
}
|
||||
|
||||
public static class ChargeFailurePaymentRequired extends SubscriptionException {
|
||||
|
||||
private final PaymentProvider processor;
|
||||
private final ChargeFailure chargeFailure;
|
||||
|
||||
public ChargeFailurePaymentRequired(final PaymentProvider processor, final ChargeFailure chargeFailure) {
|
||||
super(null, null);
|
||||
this.processor = processor;
|
||||
this.chargeFailure = chargeFailure;
|
||||
}
|
||||
|
||||
public PaymentProvider getProcessor() {
|
||||
return processor;
|
||||
}
|
||||
|
||||
public ChargeFailure getChargeFailure() {
|
||||
return chargeFailure;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static class ProcessorException extends SubscriptionException {
|
||||
|
||||
private final PaymentProvider processor;
|
||||
private final ChargeFailure chargeFailure;
|
||||
|
||||
public ProcessorException(final PaymentProvider processor, final ChargeFailure chargeFailure) {
|
||||
super(null, null);
|
||||
this.processor = processor;
|
||||
this.chargeFailure = chargeFailure;
|
||||
}
|
||||
|
||||
public PaymentProvider getProcessor() {
|
||||
return processor;
|
||||
}
|
||||
|
||||
public ChargeFailure getChargeFailure() {
|
||||
return chargeFailure;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempted to retrieve a receipt for a subscription that hasn't yet been charged or the invoice is in the open
|
||||
* state
|
||||
*/
|
||||
public static class ReceiptRequestedForOpenPayment extends SubscriptionException {
|
||||
|
||||
public ReceiptRequestedForOpenPayment() {
|
||||
super(null, null);
|
||||
}
|
||||
}
|
||||
|
||||
public static class ProcessorConflict extends SubscriptionException {
|
||||
public ProcessorConflict() {
|
||||
super(null, null);
|
||||
}
|
||||
|
||||
public ProcessorConflict(final String message) {
|
||||
super(null, message);
|
||||
}
|
||||
}
|
||||
}
|
||||
+235
-219
@@ -4,14 +4,14 @@
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import com.stripe.exception.StripeException;
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.time.Instant;
|
||||
import java.util.EnumMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.function.BiFunction;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
@@ -21,6 +21,7 @@ import org.signal.libsignal.zkgroup.VerificationFailedException;
|
||||
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialRequest;
|
||||
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialResponse;
|
||||
import org.signal.libsignal.zkgroup.receipts.ServerZkReceiptOperations;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.controllers.SubscriptionController;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.AppleAppStoreManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.CustomerAwareSubscriptionPaymentProcessor;
|
||||
@@ -29,8 +30,14 @@ import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.ProcessorCustomer;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInformation;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentProcessor;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionForbiddenException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidArgumentsException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidLevelException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionNotFoundException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentRequiredException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorConflictException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptRequestedForOpenPaymentException;
|
||||
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
|
||||
|
||||
/**
|
||||
@@ -64,24 +71,26 @@ public class SubscriptionManager {
|
||||
* Cancel a subscription with the upstream payment provider and remove the subscription from the table
|
||||
*
|
||||
* @param subscriberCredentials Subscriber credentials derived from the subscriberId
|
||||
* @return A stage that completes when the subscription has been cancelled with the upstream payment provider and the
|
||||
* subscription has been removed from the table.
|
||||
* @throws RateLimitExceededException if rate-limited
|
||||
* @throws SubscriptionNotFoundException if the provided credentials are incorrect or the subscriber does not
|
||||
* exist
|
||||
* @throws SubscriptionInvalidArgumentsException if a precondition for cancellation was not met
|
||||
*/
|
||||
public CompletableFuture<Void> deleteSubscriber(final SubscriberCredentials subscriberCredentials) {
|
||||
return subscriptions.get(subscriberCredentials.subscriberUser(), subscriberCredentials.hmac())
|
||||
.thenCompose(getResult -> {
|
||||
if (getResult == Subscriptions.GetResult.NOT_STORED
|
||||
|| getResult == Subscriptions.GetResult.PASSWORD_MISMATCH) {
|
||||
return CompletableFuture.failedFuture(new SubscriptionException.NotFound());
|
||||
}
|
||||
return getResult.record.getProcessorCustomer()
|
||||
.map(processorCustomer -> getProcessor(processorCustomer.processor())
|
||||
.cancelAllActiveSubscriptions(processorCustomer.customerId()))
|
||||
// a missing customer ID is OK; it means the subscriber never started to add a payment method
|
||||
.orElseGet(() -> CompletableFuture.completedFuture(null));
|
||||
})
|
||||
.thenCompose(unused ->
|
||||
subscriptions.setCanceledAt(subscriberCredentials.subscriberUser(), subscriberCredentials.now()));
|
||||
public void deleteSubscriber(final SubscriberCredentials subscriberCredentials)
|
||||
throws SubscriptionNotFoundException, SubscriptionInvalidArgumentsException, RateLimitExceededException {
|
||||
final Subscriptions.GetResult getResult =
|
||||
subscriptions.get(subscriberCredentials.subscriberUser(), subscriberCredentials.hmac()).join();
|
||||
if (getResult == Subscriptions.GetResult.NOT_STORED
|
||||
|| getResult == Subscriptions.GetResult.PASSWORD_MISMATCH) {
|
||||
throw new SubscriptionNotFoundException();
|
||||
}
|
||||
|
||||
// a missing customer ID is OK; it means the subscriber never started to add a payment method, so we can skip cancelling
|
||||
if (getResult.record.getProcessorCustomer().isPresent()) {
|
||||
final ProcessorCustomer processorCustomer = getResult.record.getProcessorCustomer().get();
|
||||
getProcessor(processorCustomer.processor()).cancelAllActiveSubscriptions(processorCustomer.customerId());
|
||||
}
|
||||
subscriptions.setCanceledAt(subscriberCredentials.subscriberUser(), subscriberCredentials.now()).join();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -91,60 +100,58 @@ public class SubscriptionManager {
|
||||
* already exists, its last access time will be updated.
|
||||
*
|
||||
* @param subscriberCredentials Subscriber credentials derived from the subscriberId
|
||||
* @return A stage that completes when the subscriber has been updated.
|
||||
* @throws SubscriptionForbiddenException if the subscriber credentials were incorrect
|
||||
*/
|
||||
public CompletableFuture<Void> updateSubscriber(final SubscriberCredentials subscriberCredentials) {
|
||||
return subscriptions.get(subscriberCredentials.subscriberUser(), subscriberCredentials.hmac())
|
||||
.thenCompose(getResult -> {
|
||||
if (getResult == Subscriptions.GetResult.PASSWORD_MISMATCH) {
|
||||
return CompletableFuture.failedFuture(new SubscriptionException.Forbidden("subscriberId mismatch"));
|
||||
} else if (getResult == Subscriptions.GetResult.NOT_STORED) {
|
||||
// create a customer and write it to ddb
|
||||
return subscriptions.create(subscriberCredentials.subscriberUser(), subscriberCredentials.hmac(),
|
||||
subscriberCredentials.now())
|
||||
.thenApply(updatedRecord -> {
|
||||
if (updatedRecord == null) {
|
||||
throw ExceptionUtils.wrap(new SubscriptionException.Forbidden("subscriberId mismatch"));
|
||||
}
|
||||
return updatedRecord;
|
||||
});
|
||||
} else {
|
||||
// already exists so just touch access time and return
|
||||
return subscriptions.accessedAt(subscriberCredentials.subscriberUser(), subscriberCredentials.now())
|
||||
.thenApply(unused -> getResult.record);
|
||||
}
|
||||
})
|
||||
.thenRun(Util.NOOP);
|
||||
public void updateSubscriber(final SubscriberCredentials subscriberCredentials)
|
||||
throws SubscriptionForbiddenException {
|
||||
final Subscriptions.GetResult getResult =
|
||||
subscriptions.get(subscriberCredentials.subscriberUser(), subscriberCredentials.hmac()).join();
|
||||
|
||||
if (getResult == Subscriptions.GetResult.PASSWORD_MISMATCH) {
|
||||
throw new SubscriptionForbiddenException("subscriberId mismatch");
|
||||
} else if (getResult == Subscriptions.GetResult.NOT_STORED) {
|
||||
// create a customer and write it to ddb
|
||||
final Subscriptions.Record updatedRecord = subscriptions.create(subscriberCredentials.subscriberUser(),
|
||||
subscriberCredentials.hmac(),
|
||||
subscriberCredentials.now()).join();
|
||||
if (updatedRecord == null) {
|
||||
throw new SubscriptionForbiddenException("subscriberId mismatch");
|
||||
}
|
||||
} else {
|
||||
// already exists so just touch access time and return
|
||||
subscriptions.accessedAt(subscriberCredentials.subscriberUser(), subscriberCredentials.now()).join();
|
||||
}
|
||||
}
|
||||
|
||||
public CompletableFuture<Optional<SubscriptionInformation>> getSubscriptionInformation(
|
||||
final SubscriberCredentials subscriberCredentials) {
|
||||
return getSubscriber(subscriberCredentials).thenCompose(record -> {
|
||||
if (record.subscriptionId == null) {
|
||||
return CompletableFuture.completedFuture(Optional.empty());
|
||||
}
|
||||
final SubscriptionPaymentProcessor manager = getProcessor(record.processorCustomer.processor());
|
||||
return manager.getSubscriptionInformation(record.subscriptionId).thenApply(Optional::of);
|
||||
});
|
||||
public Optional<SubscriptionInformation> getSubscriptionInformation(
|
||||
final SubscriberCredentials subscriberCredentials)
|
||||
throws SubscriptionForbiddenException, SubscriptionNotFoundException, RateLimitExceededException {
|
||||
final Subscriptions.Record record = getSubscriber(subscriberCredentials);
|
||||
if (record.subscriptionId == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
final SubscriptionPaymentProcessor manager = getProcessor(record.processorCustomer.processor());
|
||||
return Optional.of(manager.getSubscriptionInformation(record.subscriptionId));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the subscriber record
|
||||
*
|
||||
* @param subscriberCredentials Subscriber credentials derived from the subscriberId
|
||||
* @return A stage that completes with the requested subscriber if it exists and the credentials are correct.
|
||||
* @throws SubscriptionForbiddenException if the subscriber credentials were incorrect
|
||||
* @throws SubscriptionNotFoundException if the subscriber did not exist
|
||||
*/
|
||||
public CompletableFuture<Subscriptions.Record> getSubscriber(final SubscriberCredentials subscriberCredentials) {
|
||||
return subscriptions.get(subscriberCredentials.subscriberUser(), subscriberCredentials.hmac())
|
||||
.thenApply(getResult -> {
|
||||
if (getResult == Subscriptions.GetResult.PASSWORD_MISMATCH) {
|
||||
throw ExceptionUtils.wrap(new SubscriptionException.Forbidden("subscriberId mismatch"));
|
||||
} else if (getResult == Subscriptions.GetResult.NOT_STORED) {
|
||||
throw ExceptionUtils.wrap(new SubscriptionException.NotFound());
|
||||
} else {
|
||||
return getResult.record;
|
||||
}
|
||||
});
|
||||
public Subscriptions.Record getSubscriber(final SubscriberCredentials subscriberCredentials)
|
||||
throws SubscriptionForbiddenException, SubscriptionNotFoundException {
|
||||
final Subscriptions.GetResult getResult =
|
||||
subscriptions.get(subscriberCredentials.subscriberUser(), subscriberCredentials.hmac()).join();
|
||||
if (getResult == Subscriptions.GetResult.PASSWORD_MISMATCH) {
|
||||
throw new SubscriptionForbiddenException("subscriberId mismatch");
|
||||
} else if (getResult == Subscriptions.GetResult.NOT_STORED) {
|
||||
throw new SubscriptionNotFoundException();
|
||||
} else {
|
||||
return getResult.record;
|
||||
}
|
||||
}
|
||||
|
||||
public record ReceiptResult(
|
||||
@@ -159,46 +166,50 @@ public class SubscriptionManager {
|
||||
* @param request The ZK Receipt credential request
|
||||
* @param expiration A function that takes a {@link CustomerAwareSubscriptionPaymentProcessor.ReceiptItem}
|
||||
* and returns the expiration time of the receipt
|
||||
* @return If the subscription had a valid payment, the requested ZK receipt credential
|
||||
* @return the requested ZK receipt credential
|
||||
* @throws SubscriptionForbiddenException if the subscriber credentials were incorrect
|
||||
* @throws SubscriptionNotFoundException if the subscriber did not exist or did not have a
|
||||
* subscription attached
|
||||
* @throws SubscriptionInvalidArgumentsException if the receipt credential request failed verification
|
||||
* @throws SubscriptionPaymentRequiredException if the subscription is in a state does not grant the
|
||||
* user an entitlement
|
||||
* @throws SubscriptionReceiptRequestedForOpenPaymentException if a receipt was requested while a payment transaction
|
||||
* was still open
|
||||
* @throws RateLimitExceededException if rate-limited
|
||||
*/
|
||||
public CompletableFuture<ReceiptResult> createReceiptCredentials(
|
||||
public ReceiptResult createReceiptCredentials(
|
||||
final SubscriberCredentials subscriberCredentials,
|
||||
final SubscriptionController.GetReceiptCredentialsRequest request,
|
||||
final Function<CustomerAwareSubscriptionPaymentProcessor.ReceiptItem, Instant> expiration) {
|
||||
return getSubscriber(subscriberCredentials).thenCompose(record -> {
|
||||
if (record.subscriptionId == null) {
|
||||
return CompletableFuture.failedFuture(new SubscriptionException.NotFound());
|
||||
}
|
||||
final Function<CustomerAwareSubscriptionPaymentProcessor.ReceiptItem, Instant> expiration)
|
||||
throws SubscriptionForbiddenException, SubscriptionNotFoundException, SubscriptionInvalidArgumentsException, SubscriptionPaymentRequiredException, RateLimitExceededException, SubscriptionReceiptRequestedForOpenPaymentException {
|
||||
final Subscriptions.Record record = getSubscriber(subscriberCredentials);
|
||||
if (record.subscriptionId == null) {
|
||||
throw new SubscriptionNotFoundException();
|
||||
}
|
||||
|
||||
ReceiptCredentialRequest receiptCredentialRequest;
|
||||
try {
|
||||
receiptCredentialRequest = new ReceiptCredentialRequest(request.receiptCredentialRequest());
|
||||
} catch (InvalidInputException e) {
|
||||
return CompletableFuture.failedFuture(
|
||||
new SubscriptionException.InvalidArguments("invalid receipt credential request", e));
|
||||
}
|
||||
ReceiptCredentialRequest receiptCredentialRequest;
|
||||
try {
|
||||
receiptCredentialRequest = new ReceiptCredentialRequest(request.receiptCredentialRequest());
|
||||
} catch (InvalidInputException e) {
|
||||
throw new SubscriptionInvalidArgumentsException("invalid receipt credential request", e);
|
||||
}
|
||||
|
||||
final PaymentProvider processor = record.getProcessorCustomer().orElseThrow().processor();
|
||||
final SubscriptionPaymentProcessor manager = getProcessor(processor);
|
||||
return manager.getReceiptItem(record.subscriptionId)
|
||||
.thenCompose(receipt -> issuedReceiptsManager.recordIssuance(
|
||||
receipt.itemId(), manager.getProvider(), receiptCredentialRequest,
|
||||
subscriberCredentials.now())
|
||||
.thenApply(unused -> receipt))
|
||||
.thenApply(receipt -> {
|
||||
ReceiptCredentialResponse receiptCredentialResponse;
|
||||
try {
|
||||
receiptCredentialResponse = zkReceiptOperations.issueReceiptCredential(
|
||||
receiptCredentialRequest,
|
||||
expiration.apply(receipt).getEpochSecond(),
|
||||
receipt.level());
|
||||
} catch (VerificationFailedException e) {
|
||||
throw ExceptionUtils.wrap(
|
||||
new SubscriptionException.InvalidArguments("receipt credential request failed verification", e));
|
||||
}
|
||||
return new ReceiptResult(receiptCredentialResponse, receipt, processor);
|
||||
});
|
||||
});
|
||||
final PaymentProvider processor = record.getProcessorCustomer().orElseThrow().processor();
|
||||
final SubscriptionPaymentProcessor manager = getProcessor(processor);
|
||||
final SubscriptionPaymentProcessor.ReceiptItem receipt = manager.getReceiptItem(record.subscriptionId);
|
||||
issuedReceiptsManager
|
||||
.recordIssuance(receipt.itemId(), manager.getProvider(), receiptCredentialRequest, subscriberCredentials.now())
|
||||
.join();
|
||||
ReceiptCredentialResponse receiptCredentialResponse;
|
||||
try {
|
||||
receiptCredentialResponse = zkReceiptOperations.issueReceiptCredential(
|
||||
receiptCredentialRequest,
|
||||
expiration.apply(receipt).getEpochSecond(),
|
||||
receipt.level());
|
||||
} catch (VerificationFailedException e) {
|
||||
throw new SubscriptionInvalidArgumentsException("receipt credential request failed verification", e);
|
||||
}
|
||||
return new ReceiptResult(receiptCredentialResponse, receipt, processor);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -219,37 +230,35 @@ public class SubscriptionManager {
|
||||
* @param <T> A payment processor that has a notion of server-managed customers
|
||||
* @param <R> The return type of the paymentSetupFunction, which should be used by a client
|
||||
* to configure the newly created payment method
|
||||
* @return A stage that completes when the payment method has been created in the payment processor and the table has
|
||||
* been updated
|
||||
* @return The return value of the paymentSetupFunction
|
||||
* @throws SubscriptionForbiddenException if the subscriber credentials were incorrect
|
||||
* @throws SubscriptionNotFoundException if the subscriber did not exist or did not have a subscription
|
||||
* attached
|
||||
* @throws SubscriptionProcessorConflictException if the new payment processor the existing processor associated with
|
||||
* the subscriberId
|
||||
*/
|
||||
public <T extends CustomerAwareSubscriptionPaymentProcessor, R> CompletableFuture<R> addPaymentMethodToCustomer(
|
||||
public <T extends CustomerAwareSubscriptionPaymentProcessor, R> R addPaymentMethodToCustomer(
|
||||
final SubscriberCredentials subscriberCredentials,
|
||||
final T subscriptionPaymentProcessor,
|
||||
final ClientPlatform clientPlatform,
|
||||
final BiFunction<T, String, CompletableFuture<R>> paymentSetupFunction) {
|
||||
return this.getSubscriber(subscriberCredentials).thenCompose(record -> record.getProcessorCustomer()
|
||||
.map(ProcessorCustomer::processor)
|
||||
.map(processor -> {
|
||||
if (processor != subscriptionPaymentProcessor.getProvider()) {
|
||||
return CompletableFuture.<Subscriptions.Record>failedFuture(
|
||||
new SubscriptionException.ProcessorConflict("existing processor does not match"));
|
||||
}
|
||||
return CompletableFuture.completedFuture(record);
|
||||
})
|
||||
.orElseGet(() -> subscriptionPaymentProcessor
|
||||
.createCustomer(subscriberCredentials.subscriberUser(), clientPlatform)
|
||||
.thenApply(ProcessorCustomer::customerId)
|
||||
.thenCompose(customerId -> subscriptions.setProcessorAndCustomerId(record,
|
||||
new ProcessorCustomer(customerId, subscriptionPaymentProcessor.getProvider()),
|
||||
Instant.now()))))
|
||||
.thenCompose(updatedRecord -> {
|
||||
final String customerId = updatedRecord.getProcessorCustomer()
|
||||
.filter(pc -> pc.processor().equals(subscriptionPaymentProcessor.getProvider()))
|
||||
.orElseThrow(() ->
|
||||
ExceptionUtils.wrap(new SubscriptionException(null, "record should not be missing customer")))
|
||||
.customerId();
|
||||
return paymentSetupFunction.apply(subscriptionPaymentProcessor, customerId);
|
||||
});
|
||||
final BiFunction<T, String, R> paymentSetupFunction)
|
||||
throws SubscriptionForbiddenException, SubscriptionNotFoundException, SubscriptionProcessorConflictException {
|
||||
|
||||
Subscriptions.Record record = this.getSubscriber(subscriberCredentials);
|
||||
if (record.getProcessorCustomer().isEmpty()) {
|
||||
final ProcessorCustomer pc = subscriptionPaymentProcessor
|
||||
.createCustomer(subscriberCredentials.subscriberUser(), clientPlatform);
|
||||
record = subscriptions.setProcessorAndCustomerId(record,
|
||||
new ProcessorCustomer(pc.customerId(), subscriptionPaymentProcessor.getProvider()),
|
||||
Instant.now()).join();
|
||||
}
|
||||
final ProcessorCustomer processorCustomer = record.getProcessorCustomer()
|
||||
.orElseThrow(() -> new UncheckedIOException(new IOException("processor must now exist")));
|
||||
|
||||
if (processorCustomer.processor() != subscriptionPaymentProcessor.getProvider()) {
|
||||
throw new SubscriptionProcessorConflictException("existing processor does not match");
|
||||
}
|
||||
return paymentSetupFunction.apply(subscriptionPaymentProcessor, processorCustomer.customerId());
|
||||
}
|
||||
|
||||
public interface LevelTransitionValidator {
|
||||
@@ -282,9 +291,15 @@ public class SubscriptionManager {
|
||||
* @param subscriptionTemplateId Specifies the product associated with the provided level within the payment
|
||||
* processor
|
||||
* @param transitionValidator A function that checks if the level update is valid
|
||||
* @return A stage that completes when the level has been updated in the payment processor and the table
|
||||
* @throws SubscriptionInvalidArgumentsException if the transitionValidator failed for the level transition, or the
|
||||
* subscription could not be created because the payment provider
|
||||
* requires additional action, or there was a failure because an
|
||||
* idempotency key was reused on a * modified request
|
||||
* @throws SubscriptionProcessorConflictException if the new payment processor the existing processor associated with
|
||||
* the subscriber
|
||||
* @throws SubscriptionProcessorException if there was no payment method on the customer
|
||||
*/
|
||||
public CompletableFuture<Void> updateSubscriptionLevelForCustomer(
|
||||
public void updateSubscriptionLevelForCustomer(
|
||||
final SubscriberCredentials subscriberCredentials,
|
||||
final Subscriptions.Record record,
|
||||
final CustomerAwareSubscriptionPaymentProcessor processor,
|
||||
@@ -292,50 +307,45 @@ public class SubscriptionManager {
|
||||
final String currency,
|
||||
final String idempotencyKey,
|
||||
final String subscriptionTemplateId,
|
||||
final LevelTransitionValidator transitionValidator) {
|
||||
final LevelTransitionValidator transitionValidator)
|
||||
throws SubscriptionInvalidArgumentsException, SubscriptionProcessorConflictException, SubscriptionProcessorException {
|
||||
|
||||
return Optional.ofNullable(record.subscriptionId)
|
||||
if (record.subscriptionId != null) {
|
||||
// we already have a subscription in our records so let's check the level and currency,
|
||||
// and only change it if needed
|
||||
final Object subscription = processor.getSubscription(record.subscriptionId);
|
||||
final CustomerAwareSubscriptionPaymentProcessor.LevelAndCurrency existingLevelAndCurrency =
|
||||
processor.getLevelAndCurrencyForSubscription(subscription);
|
||||
final CustomerAwareSubscriptionPaymentProcessor.LevelAndCurrency desiredLevelAndCurrency =
|
||||
new CustomerAwareSubscriptionPaymentProcessor.LevelAndCurrency(level, currency.toLowerCase(Locale.ROOT));
|
||||
if (existingLevelAndCurrency.equals(desiredLevelAndCurrency)) {
|
||||
return;
|
||||
}
|
||||
if (!transitionValidator.isTransitionValid(existingLevelAndCurrency.level(), level)) {
|
||||
throw new SubscriptionInvalidLevelException();
|
||||
}
|
||||
final CustomerAwareSubscriptionPaymentProcessor.SubscriptionId updatedSubscriptionId =
|
||||
processor.updateSubscription(subscription, subscriptionTemplateId, level, idempotencyKey);
|
||||
|
||||
// we already have a subscription in our records so let's check the level and currency,
|
||||
// and only change it if needed
|
||||
.map(subId -> processor
|
||||
.getSubscription(subId)
|
||||
.thenCompose(subscription -> processor.getLevelAndCurrencyForSubscription(subscription)
|
||||
.thenCompose(existingLevelAndCurrency -> {
|
||||
if (existingLevelAndCurrency.equals(
|
||||
new CustomerAwareSubscriptionPaymentProcessor.LevelAndCurrency(level,
|
||||
currency.toLowerCase(Locale.ROOT)))) {
|
||||
return CompletableFuture.completedFuture(null);
|
||||
}
|
||||
if (!transitionValidator.isTransitionValid(existingLevelAndCurrency.level(), level)) {
|
||||
return CompletableFuture.failedFuture(new SubscriptionException.InvalidLevel());
|
||||
}
|
||||
return processor.updateSubscription(subscription, subscriptionTemplateId, level, idempotencyKey)
|
||||
.thenCompose(updatedSubscription ->
|
||||
subscriptions.subscriptionLevelChanged(subscriberCredentials.subscriberUser(),
|
||||
subscriberCredentials.now(),
|
||||
level, updatedSubscription.id()));
|
||||
})))
|
||||
subscriptions.subscriptionLevelChanged(subscriberCredentials.subscriberUser(),
|
||||
subscriberCredentials.now(),
|
||||
level,
|
||||
updatedSubscriptionId.id()).join();
|
||||
} else {
|
||||
// Otherwise, we don't have a subscription yet so create it and then record the subscription id
|
||||
long lastSubscriptionCreatedAt = record.subscriptionCreatedAt != null
|
||||
? record.subscriptionCreatedAt.getEpochSecond()
|
||||
: 0;
|
||||
|
||||
// Otherwise, we don't have a subscription yet so create it and then record the subscription id
|
||||
.orElseGet(() -> {
|
||||
long lastSubscriptionCreatedAt = record.subscriptionCreatedAt != null
|
||||
? record.subscriptionCreatedAt.getEpochSecond()
|
||||
: 0;
|
||||
final CustomerAwareSubscriptionPaymentProcessor.SubscriptionId subscription = processor.createSubscription(
|
||||
record.processorCustomer.customerId(),
|
||||
subscriptionTemplateId,
|
||||
level,
|
||||
lastSubscriptionCreatedAt);
|
||||
subscriptions.subscriptionCreated(
|
||||
subscriberCredentials.subscriberUser(), subscription.id(), subscriberCredentials.now(), level);
|
||||
|
||||
return processor.createSubscription(record.processorCustomer.customerId(),
|
||||
subscriptionTemplateId,
|
||||
level,
|
||||
lastSubscriptionCreatedAt)
|
||||
.exceptionally(ExceptionUtils.exceptionallyHandler(StripeException.class, stripeException -> {
|
||||
if ("subscription_payment_intent_requires_action".equals(stripeException.getCode())) {
|
||||
throw ExceptionUtils.wrap(new SubscriptionException.PaymentRequiresAction());
|
||||
}
|
||||
throw ExceptionUtils.wrap(stripeException);
|
||||
}))
|
||||
.thenCompose(subscription -> subscriptions.subscriptionCreated(
|
||||
subscriberCredentials.subscriberUser(), subscription.id(), subscriberCredentials.now(), level));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -345,49 +355,50 @@ public class SubscriptionManager {
|
||||
* @param googlePlayBillingManager Performs play billing API operations
|
||||
* @param purchaseToken The client provided purchaseToken that represents a purchased subscription in the
|
||||
* play store
|
||||
* @return A stage that completes with the subscription level for the accepted subscription
|
||||
* @return the subscription level for the accepted subscription
|
||||
* @throws SubscriptionForbiddenException if the subscriber credentials were incorrect
|
||||
* @throws SubscriptionNotFoundException if the subscriber did not exist or did not have a subscription
|
||||
* attached
|
||||
* @throws SubscriptionProcessorConflictException if the new payment processor the existing processor associated with
|
||||
* the subscriberId
|
||||
* @throws SubscriptionPaymentRequiredException if the subscription is not in a state that grants the user an
|
||||
* entitlement
|
||||
* @throws RateLimitExceededException if rate-limited
|
||||
*/
|
||||
public CompletableFuture<Long> updatePlayBillingPurchaseToken(
|
||||
public long updatePlayBillingPurchaseToken(
|
||||
final SubscriberCredentials subscriberCredentials,
|
||||
final GooglePlayBillingManager googlePlayBillingManager,
|
||||
final String purchaseToken) {
|
||||
final String purchaseToken)
|
||||
throws SubscriptionProcessorConflictException, SubscriptionForbiddenException, SubscriptionNotFoundException, RateLimitExceededException, SubscriptionPaymentRequiredException {
|
||||
|
||||
// For IAP providers, the subscriptionId and the customerId are both just the purchaseToken. Changes to the
|
||||
// subscription always just result in a new purchaseToken
|
||||
final ProcessorCustomer pc = new ProcessorCustomer(purchaseToken, PaymentProvider.GOOGLE_PLAY_BILLING);
|
||||
|
||||
return getSubscriber(subscriberCredentials)
|
||||
final Subscriptions.Record record = getSubscriber(subscriberCredentials);
|
||||
|
||||
// Check the record for an existing subscription
|
||||
.thenCompose(record -> {
|
||||
if (record.processorCustomer != null
|
||||
&& record.processorCustomer.processor() != PaymentProvider.GOOGLE_PLAY_BILLING) {
|
||||
return CompletableFuture.failedFuture(
|
||||
new SubscriptionException.ProcessorConflict("existing processor does not match"));
|
||||
}
|
||||
// Check the record for an existing subscription
|
||||
if (record.processorCustomer != null
|
||||
&& record.processorCustomer.processor() != PaymentProvider.GOOGLE_PLAY_BILLING) {
|
||||
throw new SubscriptionProcessorConflictException("existing processor does not match");
|
||||
}
|
||||
|
||||
// If we're replacing an existing purchaseToken, cancel it first
|
||||
return Optional.ofNullable(record.processorCustomer)
|
||||
.map(ProcessorCustomer::customerId)
|
||||
.filter(existingToken -> !purchaseToken.equals(existingToken))
|
||||
.map(googlePlayBillingManager::cancelAllActiveSubscriptions)
|
||||
.orElseGet(() -> CompletableFuture.completedFuture(null))
|
||||
.thenApply(ignored -> record);
|
||||
})
|
||||
// If we're replacing an existing purchaseToken, cancel it first
|
||||
if (record.processorCustomer != null && !purchaseToken.equals(record.processorCustomer.customerId())) {
|
||||
googlePlayBillingManager.cancelAllActiveSubscriptions(record.processorCustomer.customerId());
|
||||
}
|
||||
|
||||
// Validate and set the purchaseToken
|
||||
.thenCompose(record -> googlePlayBillingManager
|
||||
// Validating ensures we don't allow a user-determined token that's totally bunk into the subscription manager,
|
||||
// but we don't want to acknowledge it until it's successfully persisted.
|
||||
final GooglePlayBillingManager.ValidatedToken validatedToken = googlePlayBillingManager.validateToken(purchaseToken);
|
||||
|
||||
// Validating ensures we don't allow a user-determined token that's totally bunk into the subscription manager,
|
||||
// but we don't want to acknowledge it until it's successfully persisted.
|
||||
.validateToken(purchaseToken)
|
||||
// Store the valid purchaseToken with the subscriber
|
||||
subscriptions.setIapPurchase(record, pc, purchaseToken, validatedToken.getLevel(), subscriberCredentials.now());
|
||||
|
||||
// Store the purchaseToken with the subscriber
|
||||
.thenCompose(validatedToken -> subscriptions.setIapPurchase(
|
||||
record, pc, purchaseToken, validatedToken.getLevel(), subscriberCredentials.now())
|
||||
// Now that the purchaseToken is durable, we can acknowledge it
|
||||
.thenCompose(ignore -> validatedToken.acknowledgePurchase())
|
||||
.thenApply(ignore -> validatedToken.getLevel())));
|
||||
// Now that the purchaseToken is durable, we can acknowledge it
|
||||
validatedToken.acknowledgePurchase();
|
||||
|
||||
return validatedToken.getLevel();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -397,32 +408,37 @@ public class SubscriptionManager {
|
||||
* @param appleAppStoreManager Performs app store API operations
|
||||
* @param originalTransactionId The client provided originalTransactionId that represents a purchased subscription in
|
||||
* the app store
|
||||
* @return A stage that completes with the subscription level for the accepted subscription
|
||||
* @return the subscription level for the accepted subscription
|
||||
* @throws SubscriptionForbiddenException if the subscriber credentials are incorrect
|
||||
* @throws SubscriptionNotFoundException if the originalTransactionId does not exist
|
||||
* @throws SubscriptionProcessorConflictException if the new payment processor the existing processor associated with
|
||||
* the subscriber
|
||||
* @throws SubscriptionInvalidArgumentsException if the originalTransactionId is malformed or does not represent a
|
||||
* valid subscription
|
||||
* @throws SubscriptionPaymentRequiredException if the subscription is not in a state that grants the user an
|
||||
* entitlement
|
||||
* @throws RateLimitExceededException if rate-limited
|
||||
*/
|
||||
public CompletableFuture<Long> updateAppStoreTransactionId(
|
||||
public long updateAppStoreTransactionId(
|
||||
final SubscriberCredentials subscriberCredentials,
|
||||
final AppleAppStoreManager appleAppStoreManager,
|
||||
final String originalTransactionId) {
|
||||
final String originalTransactionId)
|
||||
throws SubscriptionForbiddenException, SubscriptionNotFoundException, SubscriptionProcessorConflictException, SubscriptionInvalidArgumentsException, SubscriptionPaymentRequiredException, RateLimitExceededException {
|
||||
|
||||
return getSubscriber(subscriberCredentials).thenCompose(record -> {
|
||||
if (record.processorCustomer != null
|
||||
&& record.processorCustomer.processor() != PaymentProvider.APPLE_APP_STORE) {
|
||||
return CompletableFuture.failedFuture(
|
||||
new SubscriptionException.ProcessorConflict("existing processor does not match"));
|
||||
}
|
||||
final Subscriptions.Record record = getSubscriber(subscriberCredentials);
|
||||
if (record.processorCustomer != null
|
||||
&& record.processorCustomer.processor() != PaymentProvider.APPLE_APP_STORE) {
|
||||
throw new SubscriptionProcessorConflictException("existing processor does not match");
|
||||
}
|
||||
|
||||
// For IAP providers, the subscriptionId and the customerId are both just the identifier for the subscription in
|
||||
// the provider (in this case, the originalTransactionId). Changes to the subscription always just result in a new
|
||||
// originalTransactionId
|
||||
final ProcessorCustomer pc = new ProcessorCustomer(originalTransactionId, PaymentProvider.APPLE_APP_STORE);
|
||||
|
||||
return appleAppStoreManager
|
||||
.validateTransaction(originalTransactionId)
|
||||
.thenCompose(level -> subscriptions
|
||||
.setIapPurchase(record, pc, originalTransactionId, level, subscriberCredentials.now())
|
||||
.thenApply(ignore -> level));
|
||||
});
|
||||
// For IAP providers, the subscriptionId and the customerId are both just the identifier for the subscription in
|
||||
// the provider (in this case, the originalTransactionId). Changes to the subscription always just result in a new
|
||||
// originalTransactionId
|
||||
final ProcessorCustomer pc = new ProcessorCustomer(originalTransactionId, PaymentProvider.APPLE_APP_STORE);
|
||||
|
||||
final Long level = appleAppStoreManager.validateTransaction(originalTransactionId);
|
||||
subscriptions.setIapPurchase(record, pc, originalTransactionId, level, subscriberCredentials.now()).join();
|
||||
return level;
|
||||
}
|
||||
|
||||
private SubscriptionPaymentProcessor getProcessor(PaymentProvider provider) {
|
||||
|
||||
+202
-65
@@ -8,17 +8,21 @@ import com.apple.foundationdb.tuple.Tuple;
|
||||
import com.apple.foundationdb.tuple.Versionstamp;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.common.hash.Hashing;
|
||||
import io.dropwizard.util.DataSize;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.util.Conversions;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
|
||||
/// An implementation of a message store backed by FoundationDB.
|
||||
///
|
||||
@@ -38,7 +42,21 @@ public class FoundationDbMessageStore {
|
||||
private final Clock clock;
|
||||
|
||||
private static final Subspace MESSAGES_SUBSPACE = new Subspace(Tuple.from("M"));
|
||||
private static final int MAX_SECONDS_SINCE_UPDATE_FOR_PRESENCE = 300;
|
||||
private static final Duration PRESENCE_STALE_THRESHOLD = Duration.ofMinutes(5);
|
||||
|
||||
/// The (approximate) transaction size beyond which we do not add more messages in a transaction. The estimated size
|
||||
/// includes only message payloads (and not key reads/writes) which we assume will dominate the total
|
||||
/// transaction size. Note that the FDB [docs](https://apple.github.io/foundationdb/known-limitations.html) currently
|
||||
/// suggest a limit of 1MB to avoid performance issues, although the hard limit is 10MB
|
||||
private static final long MAX_MESSAGE_CHUNK_SIZE = DataSize.megabytes(1).toBytes();
|
||||
|
||||
/// Result of inserting a message for a particular device
|
||||
///
|
||||
/// @param versionstamp the versionstamp of the transaction in which this device's message was inserted, empty
|
||||
/// otherwise
|
||||
/// @param present whether the device is online
|
||||
public record InsertResult(Optional<Versionstamp> versionstamp, boolean present) {
|
||||
}
|
||||
|
||||
public FoundationDbMessageStore(final Database[] databases, final Executor executor, final Clock clock) {
|
||||
this.databases = databases;
|
||||
@@ -46,75 +64,195 @@ public class FoundationDbMessageStore {
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
/// Insert a message bundle for a set of devices belonging to a single recipient. A message may not be inserted if the
|
||||
/// device is not present (as determined from its presence key) and the message is ephemeral. If all messages in the
|
||||
/// bundle don't end up being inserted, we won't return a versionstamp since the transaction was read-only.
|
||||
/// Convenience method for inserting a single recipient message bundle. See [#insert(Map)] for details.
|
||||
///
|
||||
/// @param aci destination account identifier
|
||||
/// @param messagesByDeviceId a map of deviceId => message envelope
|
||||
/// @return a future that completes with a [Versionstamp] of the committed transaction if at least one message was
|
||||
/// inserted
|
||||
public CompletableFuture<Optional<Versionstamp>> insert(final AciServiceIdentifier aci,
|
||||
/// @param aciServiceIdentifier accountId of the recipient
|
||||
/// @param messagesByDeviceId a map of message envelopes by deviceId to be inserted
|
||||
/// @return a future that yields a map deviceId => the presence state and versionstamp of the transaction in which the
|
||||
/// device's message was inserted (if any)
|
||||
public CompletableFuture<Map<Byte, InsertResult>> insert(final AciServiceIdentifier aciServiceIdentifier,
|
||||
final Map<Byte, MessageProtos.Envelope> messagesByDeviceId) {
|
||||
// We use Database#runAsync and not Database#run here because the latter would commit the transaction synchronously
|
||||
// and we would like to avoid any potential blocking in native code that could unexpectedly pin virtual threads. See https://forums.foundationdb.org/t/fdbdatabase-usage-from-java-api/593/2
|
||||
// for details.
|
||||
return getShardForAci(aci).runAsync(transaction -> insert(aci, messagesByDeviceId, transaction)
|
||||
.thenApply(hasMutations -> {
|
||||
if (hasMutations) {
|
||||
return transaction.getVersionstamp();
|
||||
}
|
||||
return CompletableFuture.completedFuture((byte[]) null);
|
||||
}))
|
||||
.thenComposeAsync(Function.identity(), executor)
|
||||
.thenApply(versionstampBytes -> Optional.ofNullable(versionstampBytes).map(Versionstamp::complete));
|
||||
}
|
||||
|
||||
private CompletableFuture<Boolean> insert(final AciServiceIdentifier aci,
|
||||
final Map<Byte, MessageProtos.Envelope> messagesByDeviceId,
|
||||
final Transaction transaction) {
|
||||
final List<CompletableFuture<Pair<Boolean, Boolean>>> messageInsertFutures = messagesByDeviceId.entrySet()
|
||||
.stream()
|
||||
.map(e -> {
|
||||
final byte deviceId = e.getKey();
|
||||
final MessageProtos.Envelope message = e.getValue();
|
||||
final byte[] presenceKey = getPresenceKey(aci, deviceId);
|
||||
return transaction.get(presenceKey)
|
||||
.thenApply(this::isClientPresent)
|
||||
.thenApply(isPresent -> {
|
||||
boolean hasMutations = false;
|
||||
if (isPresent || !message.getEphemeral()) {
|
||||
final Subspace deviceQueueSubspace = getDeviceQueueSubspace(aci, deviceId);
|
||||
transaction.mutate(MutationType.SET_VERSIONSTAMPED_KEY,
|
||||
deviceQueueSubspace.packWithVersionstamp(Tuple.from(
|
||||
Versionstamp.incomplete())), message.toByteArray());
|
||||
hasMutations = true;
|
||||
}
|
||||
return new Pair<>(isPresent, hasMutations);
|
||||
});
|
||||
})
|
||||
.toList();
|
||||
return CompletableFuture.allOf(messageInsertFutures.toArray(CompletableFuture[]::new))
|
||||
.thenApply(_ -> {
|
||||
final boolean anyClientPresent = messageInsertFutures
|
||||
.stream()
|
||||
.anyMatch(future -> future.join().first());
|
||||
final boolean hasMutations = messageInsertFutures
|
||||
.stream()
|
||||
.anyMatch(future -> future.join().second());
|
||||
if (anyClientPresent && hasMutations) {
|
||||
transaction.mutate(MutationType.SET_VERSIONSTAMPED_VALUE, getMessagesAvailableWatchKey(aci),
|
||||
Tuple.from(Versionstamp.incomplete()).packWithVersionstamp());
|
||||
}
|
||||
return hasMutations;
|
||||
return insert(Map.of(aciServiceIdentifier, messagesByDeviceId))
|
||||
.thenApply(resultsByServiceIdentifier -> {
|
||||
assert resultsByServiceIdentifier.size() == 1;
|
||||
|
||||
return resultsByServiceIdentifier.get(aciServiceIdentifier);
|
||||
});
|
||||
}
|
||||
|
||||
private Database getShardForAci(final AciServiceIdentifier aci) {
|
||||
/// Insert a multi-recipient message bundle. Destination ACIs are grouped by shard number. Each shard then starts a
|
||||
/// potentially multi-transaction operation. Messages are inserted in chunks to avoid transaction size limits.
|
||||
///
|
||||
/// @param messagesByServiceIdentifier a map of accountId to message envelopes by deviceId
|
||||
/// @return a future that yields a map containing the presence states of devices and versionstamps corresponding to
|
||||
/// committed transactions during this operation
|
||||
///
|
||||
/// @implNote All messages belonging to the same recipient are always committed in the same transaction for
|
||||
/// simplicity. A message may not be inserted if the device is not present (as determined from its presence key) and
|
||||
/// the message is ephemeral. If no messages in a transaction end up being inserted, we won't commit it since the
|
||||
/// transaction was read-only. As such, no corresponding versionstamp is generated.
|
||||
public CompletableFuture<Map<AciServiceIdentifier, Map<Byte, InsertResult>>> insert(
|
||||
final Map<AciServiceIdentifier, Map<Byte, MessageProtos.Envelope>> messagesByServiceIdentifier) {
|
||||
|
||||
if (messagesByServiceIdentifier.entrySet()
|
||||
.stream()
|
||||
.anyMatch(entry -> entry.getValue().isEmpty())) {
|
||||
throw new IllegalArgumentException("One or more message bundles is empty");
|
||||
}
|
||||
|
||||
final Map<Integer, List<Map.Entry<AciServiceIdentifier, Map<Byte, MessageProtos.Envelope>>>> messagesByShardId =
|
||||
messagesByServiceIdentifier.entrySet().stream()
|
||||
.collect(Collectors.groupingBy(entry -> hashAciToShardNumber(entry.getKey())));
|
||||
|
||||
final List<CompletableFuture<Map<AciServiceIdentifier, Map<Byte, InsertResult>>>> chunkFutures =
|
||||
new ArrayList<>();
|
||||
|
||||
messagesByShardId.forEach((shardId, messagesForShard) -> {
|
||||
final Database shard = databases[shardId];
|
||||
|
||||
int start = 0, current = 0;
|
||||
int estimatedTransactionSize = 0;
|
||||
|
||||
while (current < messagesForShard.size()) {
|
||||
estimatedTransactionSize += messagesForShard.get(current).getValue().values()
|
||||
.stream()
|
||||
.mapToInt(MessageProtos.Envelope::getSerializedSize)
|
||||
.sum();
|
||||
|
||||
if (estimatedTransactionSize > MAX_MESSAGE_CHUNK_SIZE) {
|
||||
chunkFutures.add(insertChunk(shard, messagesForShard.subList(start, current)));
|
||||
|
||||
start = current;
|
||||
estimatedTransactionSize = 0;
|
||||
} else {
|
||||
current++;
|
||||
}
|
||||
}
|
||||
|
||||
assert start < messagesForShard.size();
|
||||
chunkFutures.add(insertChunk(shard, messagesForShard.subList(start, messagesForShard.size())));
|
||||
});
|
||||
|
||||
return CompletableFuture.allOf(chunkFutures.toArray(CompletableFuture[]::new))
|
||||
.thenApply(_ -> chunkFutures.stream()
|
||||
.map(CompletableFuture::join)
|
||||
.reduce(new HashMap<>(), (a, b) -> {
|
||||
a.putAll(b);
|
||||
return a;
|
||||
}));
|
||||
}
|
||||
|
||||
private CompletableFuture<Map<AciServiceIdentifier, Map<Byte, InsertResult>>> insertChunk(
|
||||
final Database database,
|
||||
final List<Map.Entry<AciServiceIdentifier, Map<Byte, MessageProtos.Envelope>>> messagesByAccountIdentifier) {
|
||||
|
||||
final Map<AciServiceIdentifier, CompletableFuture<Map<Byte, Boolean>>> insertFuturesByAci = new HashMap<>();
|
||||
|
||||
// In a message bundle (single-recipient or MRM) the ephemerality should be the same for all envelopes, so just get the first.
|
||||
final boolean ephemeral = messagesByAccountIdentifier.stream()
|
||||
.findFirst()
|
||||
.flatMap(entry -> entry.getValue().values().stream().findFirst())
|
||||
.map(MessageProtos.Envelope::getEphemeral)
|
||||
.orElseThrow(() -> new IllegalStateException("One or more bundles is empty"));
|
||||
|
||||
return database.runAsync(transaction -> {
|
||||
messagesByAccountIdentifier.forEach(entry ->
|
||||
insertFuturesByAci.put(entry.getKey(), insert(entry.getKey(), entry.getValue(), transaction)));
|
||||
|
||||
return CompletableFuture.allOf(insertFuturesByAci.values().toArray(CompletableFuture[]::new))
|
||||
.thenApply(_ -> {
|
||||
final boolean anyClientPresent = insertFuturesByAci.values()
|
||||
.stream()
|
||||
.map(CompletableFuture::join)
|
||||
.flatMap(presenceByDeviceId -> presenceByDeviceId.values().stream())
|
||||
.anyMatch(isPresent -> isPresent);
|
||||
if (anyClientPresent || !ephemeral) {
|
||||
return transaction.getVersionstamp()
|
||||
.thenApply(versionstampBytes -> Optional.of(Versionstamp.complete(versionstampBytes)));
|
||||
}
|
||||
return CompletableFuture.completedFuture(Optional.<Versionstamp>empty());
|
||||
});
|
||||
})
|
||||
.thenCompose(Function.identity())
|
||||
.thenApply(maybeVersionstamp -> insertFuturesByAci.entrySet().stream()
|
||||
.collect(Collectors.toMap(Map.Entry::getKey, entry -> {
|
||||
assert entry.getValue().isDone();
|
||||
final Map<Byte, Boolean> presenceByDeviceId = entry.getValue().join();
|
||||
|
||||
return presenceByDeviceId.entrySet().stream()
|
||||
.collect(Collectors.toMap(Map.Entry::getKey, presenceEntry -> {
|
||||
final Optional<Versionstamp> insertResultVersionstamp;
|
||||
if (presenceEntry.getValue() || !ephemeral) {
|
||||
assert maybeVersionstamp.isPresent();
|
||||
insertResultVersionstamp = maybeVersionstamp;
|
||||
} else {
|
||||
insertResultVersionstamp = Optional.empty();
|
||||
}
|
||||
return new InsertResult(insertResultVersionstamp, presenceEntry.getValue());
|
||||
}));
|
||||
})));
|
||||
}
|
||||
|
||||
/// Insert a message bundle for a single recipient in an ongoing transaction.
|
||||
///
|
||||
/// @implNote A message for a device is not inserted if it is offline and the message is ephemeral. Additionally, the
|
||||
/// message watch key is updated iff at least one receiving device is present.
|
||||
///
|
||||
/// @param aci accountId of the recipient
|
||||
/// @param messagesByDeviceId map of destination deviceId => message envelopes
|
||||
/// @param transaction the ongoing transaction
|
||||
/// @return a future that yields the presence state of each destination device
|
||||
private CompletableFuture<Map<Byte, Boolean>> insert(final AciServiceIdentifier aci,
|
||||
final Map<Byte, MessageProtos.Envelope> messagesByDeviceId,
|
||||
final Transaction transaction) {
|
||||
|
||||
final Map<Byte, CompletableFuture<Boolean>> messageInsertFuturesByDeviceId = messagesByDeviceId.entrySet()
|
||||
.stream()
|
||||
.collect(Collectors.toMap(Map.Entry::getKey, e -> {
|
||||
final byte deviceId = e.getKey();
|
||||
final MessageProtos.Envelope message = e.getValue();
|
||||
final byte[] presenceKey = getPresenceKey(aci, deviceId);
|
||||
|
||||
return transaction.get(presenceKey)
|
||||
.thenApply(this::isClientPresent)
|
||||
.thenApply(isPresent -> {
|
||||
if (isPresent || !message.getEphemeral()) {
|
||||
transaction.mutate(MutationType.SET_VERSIONSTAMPED_KEY,
|
||||
getDeviceQueueSubspace(aci, deviceId)
|
||||
.packWithVersionstamp(Tuple.from(Versionstamp.incomplete())), message.toByteArray());
|
||||
}
|
||||
|
||||
return isPresent;
|
||||
});
|
||||
}));
|
||||
|
||||
return CompletableFuture.allOf(messageInsertFuturesByDeviceId.values().toArray(CompletableFuture[]::new))
|
||||
.thenApplyAsync(_ -> {
|
||||
final Map<Byte, Boolean> presenceByDeviceId = messageInsertFuturesByDeviceId.entrySet().stream()
|
||||
.collect(Collectors.toMap(Map.Entry::getKey, entry -> {
|
||||
assert entry.getValue().isDone();
|
||||
return entry.getValue().join();
|
||||
}));
|
||||
|
||||
final boolean anyClientPresent = presenceByDeviceId.values().stream().anyMatch(present -> present);
|
||||
|
||||
if (anyClientPresent) {
|
||||
transaction.mutate(MutationType.SET_VERSIONSTAMPED_VALUE, getMessagesAvailableWatchKey(aci),
|
||||
Tuple.from(Versionstamp.incomplete()).packWithVersionstamp());
|
||||
}
|
||||
|
||||
return presenceByDeviceId;
|
||||
}, executor);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
Database getShardForAci(final AciServiceIdentifier aci) {
|
||||
return databases[hashAciToShardNumber(aci)];
|
||||
}
|
||||
|
||||
private int hashAciToShardNumber(final AciServiceIdentifier aci) {
|
||||
@VisibleForTesting
|
||||
int hashAciToShardNumber(final AciServiceIdentifier aci) {
|
||||
// We use a consistent hash here to reduce the number of key remappings if we increase the number of shards
|
||||
return Hashing.consistentHash(aci.uuid().getLeastSignificantBits(), databases.length);
|
||||
}
|
||||
@@ -139,7 +277,7 @@ public class FoundationDbMessageStore {
|
||||
|
||||
@VisibleForTesting
|
||||
byte[] getPresenceKey(final AciServiceIdentifier aci, final byte deviceId) {
|
||||
return getDeviceQueueSubspace(aci, deviceId).pack("p");
|
||||
return getDeviceSubspace(aci, deviceId).pack("p");
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
@@ -151,7 +289,6 @@ public class FoundationDbMessageStore {
|
||||
// The presence value is a long with the higher order 16 bits containing a server id, and the lower 48 bits
|
||||
// containing the timestamp (seconds since epoch) that the client updates periodically.
|
||||
final long lastSeenSecondsSinceEpoch = presenceValue & 0x0000ffffffffffffL;
|
||||
return (clock.instant().getEpochSecond() - lastSeenSecondsSinceEpoch) <= MAX_SECONDS_SINCE_UPDATE_FOR_PRESENCE;
|
||||
return (clock.instant().getEpochSecond() - lastSeenSecondsSinceEpoch) <= PRESENCE_STALE_THRESHOLD.toSeconds();
|
||||
}
|
||||
|
||||
}
|
||||
+136
-136
@@ -24,6 +24,7 @@ import io.micrometer.core.instrument.Metrics;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.math.BigDecimal;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.time.Instant;
|
||||
@@ -31,14 +32,8 @@ import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Collectors;
|
||||
import javax.annotation.Nullable;
|
||||
import org.slf4j.Logger;
|
||||
@@ -46,9 +41,7 @@ import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.PaymentTime;
|
||||
import org.whispersystems.textsecuregcm.storage.SubscriptionException;
|
||||
import org.whispersystems.textsecuregcm.util.ResilienceUtil;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
|
||||
/**
|
||||
* Manages subscriptions made with the Apple App Store
|
||||
@@ -63,8 +56,6 @@ public class AppleAppStoreManager implements SubscriptionPaymentProcessor {
|
||||
|
||||
private final AppStoreServerAPIClient apiClient;
|
||||
private final SignedDataVerifier signedDataVerifier;
|
||||
private final ExecutorService executor;
|
||||
private final ScheduledExecutorService retryExecutor;
|
||||
private final Map<String, Long> productIdToLevel;
|
||||
|
||||
private static final Status[] EMPTY_STATUSES = new Status[0];
|
||||
@@ -86,12 +77,10 @@ public class AppleAppStoreManager implements SubscriptionPaymentProcessor {
|
||||
final String subscriptionGroupId,
|
||||
final Map<String, Long> productIdToLevel,
|
||||
final List<String> base64AppleRootCerts,
|
||||
@Nullable final String retryConfigurationName,
|
||||
final ExecutorService executor,
|
||||
final ScheduledExecutorService retryExecutor) {
|
||||
@Nullable final String retryConfigurationName) {
|
||||
this(new AppStoreServerAPIClient(encodedKey, keyId, issuerId, bundleId, env),
|
||||
new SignedDataVerifier(decodeRootCerts(base64AppleRootCerts), bundleId, appAppleId, env, true),
|
||||
subscriptionGroupId, productIdToLevel, retryConfigurationName, executor, retryExecutor);
|
||||
subscriptionGroupId, productIdToLevel, retryConfigurationName);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
@@ -100,25 +89,16 @@ public class AppleAppStoreManager implements SubscriptionPaymentProcessor {
|
||||
final SignedDataVerifier signedDataVerifier,
|
||||
final String subscriptionGroupId,
|
||||
final Map<String, Long> productIdToLevel,
|
||||
@Nullable final String retryConfigurationName,
|
||||
final ExecutorService executor,
|
||||
final ScheduledExecutorService retryExecutor) {
|
||||
@Nullable final String retryConfigurationName) {
|
||||
this.apiClient = apiClient;
|
||||
this.signedDataVerifier = signedDataVerifier;
|
||||
this.subscriptionGroupId = subscriptionGroupId;
|
||||
this.productIdToLevel = productIdToLevel;
|
||||
this.executor = Objects.requireNonNull(executor);
|
||||
this.retryExecutor = Objects.requireNonNull(retryExecutor);
|
||||
|
||||
final RetryConfig.Builder<HttpResponse<?>> retryConfigBuilder =
|
||||
RetryConfig.from(Optional.ofNullable(retryConfigurationName)
|
||||
this.retry = ResilienceUtil.getRetryRegistry().retry("appstore-retry", RetryConfig
|
||||
.<HttpResponse<?>>from(Optional.ofNullable(retryConfigurationName)
|
||||
.flatMap(name -> ResilienceUtil.getRetryRegistry().getConfiguration(name))
|
||||
.orElseGet(() -> ResilienceUtil.getRetryRegistry().getDefaultConfig()));
|
||||
|
||||
retryConfigBuilder.retryOnException(AppleAppStoreManager::shouldRetry);
|
||||
|
||||
this.retry = ResilienceUtil.getRetryRegistry()
|
||||
.retry(ResilienceUtil.name(AppleAppStoreManager.class, "appstore-retry"), retryConfigBuilder.build());
|
||||
.orElseGet(() -> ResilienceUtil.getRetryRegistry().getDefaultConfig()))
|
||||
.retryOnException(AppleAppStoreManager::shouldRetry).build());
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -131,16 +111,20 @@ public class AppleAppStoreManager implements SubscriptionPaymentProcessor {
|
||||
* Check if the subscription with the provided originalTransactionId is valid.
|
||||
*
|
||||
* @param originalTransactionId The originalTransactionId associated with the subscription
|
||||
* @return A stage that completes successfully when the transaction has been validated, or fails if the token does not
|
||||
* represent an active subscription.
|
||||
* @return the subscription level of the valid transaction.
|
||||
* @throws RateLimitExceededException If rate-limited
|
||||
* @throws SubscriptionNotFoundException If the provided originalTransactionId was not found
|
||||
* @throws SubscriptionPaymentRequiredException If the originalTransactionId exists but is in a state that does not
|
||||
* grant the user an entitlement
|
||||
* @throws SubscriptionInvalidArgumentsException If the transaction is valid but does not contain a subscription
|
||||
*/
|
||||
public CompletableFuture<Long> validateTransaction(final String originalTransactionId) {
|
||||
return lookup(originalTransactionId).thenApplyAsync(tx -> {
|
||||
if (!isSubscriptionActive(tx)) {
|
||||
throw ExceptionUtils.wrap(new SubscriptionException.PaymentRequired());
|
||||
}
|
||||
return getLevel(tx);
|
||||
}, executor);
|
||||
public Long validateTransaction(final String originalTransactionId)
|
||||
throws SubscriptionInvalidArgumentsException, RateLimitExceededException, SubscriptionNotFoundException, SubscriptionPaymentRequiredException {
|
||||
final DecodedTransaction tx = lookupAndValidateTransaction(originalTransactionId);
|
||||
if (!isSubscriptionActive(tx)) {
|
||||
throw new SubscriptionPaymentRequiredException();
|
||||
}
|
||||
return getLevel(tx);
|
||||
}
|
||||
|
||||
|
||||
@@ -152,125 +136,142 @@ public class AppleAppStoreManager implements SubscriptionPaymentProcessor {
|
||||
* this method.
|
||||
*
|
||||
* @param originalTransactionId The originalTransactionId associated with the subscription
|
||||
* @return A stage that completes when the subscription has successfully been cancelled
|
||||
* @throws RateLimitExceededException If rate-limited
|
||||
* @throws SubscriptionInvalidArgumentsException If the transaction is valid but does not contain a subscription, or
|
||||
* the transaction has not already been cancelled with storekit
|
||||
*/
|
||||
@Override
|
||||
public CompletableFuture<Void> cancelAllActiveSubscriptions(String originalTransactionId) {
|
||||
return lookup(originalTransactionId).thenApplyAsync(tx -> {
|
||||
public void cancelAllActiveSubscriptions(String originalTransactionId)
|
||||
throws SubscriptionInvalidArgumentsException, RateLimitExceededException {
|
||||
try {
|
||||
final DecodedTransaction tx = lookup(originalTransactionId);
|
||||
if (tx.signedTransaction.getStatus() != Status.EXPIRED &&
|
||||
tx.signedTransaction.getStatus() != Status.REVOKED &&
|
||||
tx.renewalInfo.getAutoRenewStatus() != AutoRenewStatus.OFF) {
|
||||
throw ExceptionUtils.wrap(
|
||||
new SubscriptionException.InvalidArguments("must cancel subscription with storekit before deleting"));
|
||||
throw new SubscriptionInvalidArgumentsException("must cancel subscription with storekit before deleting");
|
||||
}
|
||||
// The subscription will not auto-renew, so we can stop tracking it
|
||||
return null;
|
||||
}, executor);
|
||||
} catch (SubscriptionNotFoundException _) {
|
||||
// If the subscription is not found there is no need to do anything, so we can squash it
|
||||
}
|
||||
// The subscription will not auto-renew, so we can stop tracking it
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<SubscriptionInformation> getSubscriptionInformation(final String originalTransactionId) {
|
||||
return lookup(originalTransactionId).thenApplyAsync(tx -> {
|
||||
public SubscriptionInformation getSubscriptionInformation(final String originalTransactionId)
|
||||
throws RateLimitExceededException, SubscriptionNotFoundException {
|
||||
final DecodedTransaction tx = lookup(originalTransactionId);
|
||||
final SubscriptionStatus status = switch (tx.signedTransaction.getStatus()) {
|
||||
case ACTIVE -> SubscriptionStatus.ACTIVE;
|
||||
case BILLING_RETRY -> SubscriptionStatus.PAST_DUE;
|
||||
case BILLING_GRACE_PERIOD -> SubscriptionStatus.UNPAID;
|
||||
case EXPIRED, REVOKED -> SubscriptionStatus.CANCELED;
|
||||
};
|
||||
|
||||
final SubscriptionStatus status = switch (tx.signedTransaction.getStatus()) {
|
||||
case ACTIVE -> SubscriptionStatus.ACTIVE;
|
||||
case BILLING_RETRY -> SubscriptionStatus.PAST_DUE;
|
||||
case BILLING_GRACE_PERIOD -> SubscriptionStatus.UNPAID;
|
||||
case EXPIRED, REVOKED -> SubscriptionStatus.CANCELED;
|
||||
};
|
||||
|
||||
return new SubscriptionInformation(
|
||||
getSubscriptionPrice(tx),
|
||||
getLevel(tx),
|
||||
Instant.ofEpochMilli(tx.transaction.getOriginalPurchaseDate()),
|
||||
Instant.ofEpochMilli(tx.transaction.getExpiresDate()),
|
||||
isSubscriptionActive(tx),
|
||||
tx.renewalInfo.getAutoRenewStatus() == AutoRenewStatus.OFF,
|
||||
status,
|
||||
PaymentProvider.APPLE_APP_STORE,
|
||||
PaymentMethod.APPLE_APP_STORE,
|
||||
false,
|
||||
null);
|
||||
}, executor);
|
||||
return new SubscriptionInformation(
|
||||
getSubscriptionPrice(tx),
|
||||
getLevel(tx),
|
||||
Instant.ofEpochMilli(tx.transaction.getOriginalPurchaseDate()),
|
||||
Instant.ofEpochMilli(tx.transaction.getExpiresDate()),
|
||||
isSubscriptionActive(tx),
|
||||
tx.renewalInfo.getAutoRenewStatus() == AutoRenewStatus.OFF,
|
||||
status,
|
||||
PaymentProvider.APPLE_APP_STORE,
|
||||
PaymentMethod.APPLE_APP_STORE,
|
||||
false,
|
||||
null);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public CompletableFuture<ReceiptItem> getReceiptItem(String originalTransactionId) {
|
||||
return lookup(originalTransactionId).thenApplyAsync(tx -> {
|
||||
if (!isSubscriptionActive(tx)) {
|
||||
throw ExceptionUtils.wrap(new SubscriptionException.PaymentRequired());
|
||||
}
|
||||
public ReceiptItem getReceiptItem(String originalTransactionId)
|
||||
throws RateLimitExceededException, SubscriptionNotFoundException, SubscriptionPaymentRequiredException {
|
||||
final DecodedTransaction tx = lookup(originalTransactionId);
|
||||
if (!isSubscriptionActive(tx)) {
|
||||
throw new SubscriptionPaymentRequiredException();
|
||||
}
|
||||
|
||||
// A new transactionId might be generated if you restore a subscription on a new device. webOrderLineItemId is
|
||||
// guaranteed not to change for a specific renewal purchase.
|
||||
// See: https://developer.apple.com/documentation/appstoreservernotifications/weborderlineitemid
|
||||
final String itemId = tx.transaction.getWebOrderLineItemId();
|
||||
final PaymentTime paymentTime = PaymentTime.periodEnds(Instant.ofEpochMilli(tx.transaction.getExpiresDate()));
|
||||
// A new transactionId might be generated if you restore a subscription on a new device. webOrderLineItemId is
|
||||
// guaranteed not to change for a specific renewal purchase.
|
||||
// See: https://developer.apple.com/documentation/appstoreservernotifications/weborderlineitemid
|
||||
final String itemId = tx.transaction.getWebOrderLineItemId();
|
||||
final PaymentTime paymentTime = PaymentTime.periodEnds(Instant.ofEpochMilli(tx.transaction.getExpiresDate()));
|
||||
|
||||
return new ReceiptItem(itemId, paymentTime, getLevel(tx));
|
||||
return new ReceiptItem(itemId, paymentTime, getLevel(tx));
|
||||
|
||||
}, executor);
|
||||
}
|
||||
|
||||
private CompletableFuture<DecodedTransaction> lookup(final String originalTransactionId) {
|
||||
return getAllSubscriptions(originalTransactionId).thenApplyAsync(statuses -> {
|
||||
|
||||
final SubscriptionGroupIdentifierItem item = statuses.getData().stream()
|
||||
.filter(s -> subscriptionGroupId.equals(s.getSubscriptionGroupIdentifier())).findFirst()
|
||||
.orElseThrow(() -> ExceptionUtils.wrap(
|
||||
new SubscriptionException.InvalidArguments("transaction did not contain a backup subscription", null)));
|
||||
|
||||
final List<DecodedTransaction> txs = item.getLastTransactions().stream()
|
||||
.map(this::decode)
|
||||
.filter(decoded -> productIdToLevel.containsKey(decoded.transaction.getProductId()))
|
||||
.toList();
|
||||
|
||||
if (txs.isEmpty()) {
|
||||
throw ExceptionUtils.wrap(
|
||||
new SubscriptionException.InvalidArguments("transactionId did not include a paid subscription", null));
|
||||
}
|
||||
|
||||
if (txs.size() > 1) {
|
||||
logger.warn("Multiple matching product transactions found for transactionId {}, only considering first",
|
||||
originalTransactionId);
|
||||
}
|
||||
|
||||
if (!originalTransactionId.equals(txs.getFirst().signedTransaction.getOriginalTransactionId())) {
|
||||
// Get All Subscriptions only requires that the transaction be some transaction associated with the
|
||||
// subscription. This is too flexible, since we'd like to key on the originalTransactionId in the
|
||||
// SubscriptionManager.
|
||||
throw ExceptionUtils.wrap(
|
||||
new SubscriptionException.InvalidArguments(
|
||||
"transactionId was not the transaction's originalTransactionId", null));
|
||||
}
|
||||
|
||||
return txs.getFirst();
|
||||
}, executor).toCompletableFuture();
|
||||
private DecodedTransaction lookup(final String originalTransactionId)
|
||||
throws RateLimitExceededException, SubscriptionNotFoundException {
|
||||
try {
|
||||
return lookupAndValidateTransaction(originalTransactionId);
|
||||
} catch (SubscriptionInvalidArgumentsException e) {
|
||||
// Shouldn't happen because we previously validated this transactionId before storing it
|
||||
throw new UncheckedIOException(new IOException(e));
|
||||
}
|
||||
}
|
||||
|
||||
private CompletionStage<StatusResponse> getAllSubscriptions(final String originalTransactionId) {
|
||||
Supplier<CompletionStage<StatusResponse>> supplier = () -> CompletableFuture.supplyAsync(() -> {
|
||||
try {
|
||||
return apiClient.getAllSubscriptionStatuses(originalTransactionId, EMPTY_STATUSES);
|
||||
} catch (final APIException e) {
|
||||
Metrics.counter(GET_SUBSCRIPTION_ERROR_COUNTER_NAME, "reason", e.getApiError().name()).increment();
|
||||
throw ExceptionUtils.wrap(switch (e.getApiError()) {
|
||||
case ORIGINAL_TRANSACTION_ID_NOT_FOUND, TRANSACTION_ID_NOT_FOUND -> new SubscriptionException.NotFound();
|
||||
case RATE_LIMIT_EXCEEDED -> new RateLimitExceededException(null);
|
||||
case INVALID_ORIGINAL_TRANSACTION_ID -> new SubscriptionException.InvalidArguments(e.getApiErrorMessage());
|
||||
default -> e;
|
||||
});
|
||||
} catch (final IOException e) {
|
||||
Metrics.counter(GET_SUBSCRIPTION_ERROR_COUNTER_NAME, "reason", "io_error").increment();
|
||||
throw ExceptionUtils.wrap(e);
|
||||
}
|
||||
}, executor);
|
||||
return retry.executeCompletionStage(retryExecutor, supplier);
|
||||
private DecodedTransaction lookupAndValidateTransaction(final String originalTransactionId)
|
||||
throws SubscriptionInvalidArgumentsException, RateLimitExceededException, SubscriptionNotFoundException {
|
||||
final StatusResponse statuses = getAllSubscriptions(originalTransactionId);
|
||||
final SubscriptionGroupIdentifierItem item = statuses.getData().stream()
|
||||
.filter(s -> subscriptionGroupId.equals(s.getSubscriptionGroupIdentifier())).findFirst()
|
||||
.orElseThrow(() -> new SubscriptionInvalidArgumentsException("transaction did not contain a backup subscription", null));
|
||||
|
||||
final List<DecodedTransaction> txs = item.getLastTransactions().stream()
|
||||
.map(this::decode)
|
||||
.filter(decoded -> productIdToLevel.containsKey(decoded.transaction.getProductId()))
|
||||
.toList();
|
||||
|
||||
if (txs.isEmpty()) {
|
||||
throw new SubscriptionInvalidArgumentsException("transactionId did not include a paid subscription", null);
|
||||
}
|
||||
|
||||
if (txs.size() > 1) {
|
||||
logger.warn("Multiple matching product transactions found for transactionId {}, only considering first",
|
||||
originalTransactionId);
|
||||
}
|
||||
|
||||
if (!originalTransactionId.equals(txs.getFirst().signedTransaction.getOriginalTransactionId())) {
|
||||
// Get All Subscriptions only requires that the transaction be some transaction associated with the
|
||||
// subscription. This is too flexible, since we'd like to key on the originalTransactionId in the
|
||||
// SubscriptionManager.
|
||||
throw new SubscriptionInvalidArgumentsException("transactionId was not the transaction's originalTransactionId", null);
|
||||
}
|
||||
return txs.getFirst();
|
||||
}
|
||||
|
||||
private StatusResponse getAllSubscriptions(final String originalTransactionId)
|
||||
throws SubscriptionNotFoundException, SubscriptionInvalidArgumentsException, RateLimitExceededException {
|
||||
try {
|
||||
return retry.executeCallable(() -> {
|
||||
try {
|
||||
return apiClient.getAllSubscriptionStatuses(originalTransactionId, EMPTY_STATUSES);
|
||||
} catch (final APIException e) {
|
||||
Metrics.counter(GET_SUBSCRIPTION_ERROR_COUNTER_NAME, "reason", e.getApiError().name()).increment();
|
||||
throw switch (e.getApiError()) {
|
||||
case ORIGINAL_TRANSACTION_ID_NOT_FOUND, TRANSACTION_ID_NOT_FOUND -> new SubscriptionNotFoundException();
|
||||
case RATE_LIMIT_EXCEEDED -> new RateLimitExceededException(null);
|
||||
case INVALID_ORIGINAL_TRANSACTION_ID -> new SubscriptionInvalidArgumentsException(e.getApiErrorMessage());
|
||||
default -> e;
|
||||
};
|
||||
} catch (final IOException e) {
|
||||
Metrics.counter(GET_SUBSCRIPTION_ERROR_COUNTER_NAME, "reason", "io_error").increment();
|
||||
throw e;
|
||||
}
|
||||
});
|
||||
} catch (SubscriptionNotFoundException | SubscriptionInvalidArgumentsException | RateLimitExceededException e) {
|
||||
throw e;
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
} catch (APIException e) {
|
||||
throw new UncheckedIOException(new IOException(e));
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean shouldRetry(Throwable e) {
|
||||
return ExceptionUtils.unwrap(e) instanceof APIException apiException && switch (apiException.getApiError()) {
|
||||
return e instanceof APIException apiException && switch (apiException.getApiError()) {
|
||||
case ORIGINAL_TRANSACTION_ID_NOT_FOUND_RETRYABLE, GENERAL_INTERNAL_RETRYABLE, APP_NOT_FOUND_RETRYABLE -> true;
|
||||
default -> false;
|
||||
};
|
||||
@@ -291,7 +292,7 @@ public class AppleAppStoreManager implements SubscriptionPaymentProcessor {
|
||||
signedDataVerifier.verifyAndDecodeTransaction(tx.getSignedTransactionInfo()),
|
||||
signedDataVerifier.verifyAndDecodeRenewalInfo(tx.getSignedRenewalInfo()));
|
||||
} catch (VerificationException e) {
|
||||
throw ExceptionUtils.wrap(new IOException("Failed to verify payload from App Store Server", e));
|
||||
throw new UncheckedIOException(new IOException("Failed to verify payload from App Store Server", e));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -305,9 +306,8 @@ public class AppleAppStoreManager implements SubscriptionPaymentProcessor {
|
||||
private long getLevel(final DecodedTransaction tx) {
|
||||
final Long level = productIdToLevel.get(tx.transaction.getProductId());
|
||||
if (level == null) {
|
||||
throw ExceptionUtils.wrap(
|
||||
new SubscriptionException.InvalidArguments(
|
||||
"Transaction for unknown productId " + tx.transaction.getProductId()));
|
||||
throw new UncheckedIOException(new IOException(
|
||||
"Transaction for unknown productId " + tx.transaction.getProductId()));
|
||||
}
|
||||
return level;
|
||||
}
|
||||
|
||||
+147
-191
@@ -5,6 +5,8 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
|
||||
import com.braintree.graphql.clientoperation.TokenizePayPalBillingAgreementMutation;
|
||||
import com.braintree.graphql.clientoperation.VaultPaymentMethodMutation;
|
||||
import com.braintreegateway.BraintreeGateway;
|
||||
import com.braintreegateway.ClientTokenRequest;
|
||||
import com.braintreegateway.Customer;
|
||||
@@ -30,15 +32,12 @@ import java.time.Instant;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import javax.annotation.Nullable;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
@@ -46,8 +45,8 @@ import org.whispersystems.textsecuregcm.currency.CurrencyConversionManager;
|
||||
import org.whispersystems.textsecuregcm.http.FaultTolerantHttpClient;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.PaymentTime;
|
||||
import org.whispersystems.textsecuregcm.storage.SubscriptionException;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.util.ExecutorUtil;
|
||||
import org.whispersystems.textsecuregcm.util.GoogleApiUtil;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
|
||||
@@ -81,8 +80,7 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
|
||||
final CurrencyConversionManager currencyConversionManager,
|
||||
final PublisherInterface pubsubPublisher,
|
||||
@Nullable final String circuitBreakerConfigurationName,
|
||||
final Executor executor,
|
||||
final ScheduledExecutorService retryExecutor) {
|
||||
final Executor executor) {
|
||||
|
||||
this(new BraintreeGateway(braintreeEnvironment, braintreeMerchantId, braintreePublicKey,
|
||||
braintreePrivateKey),
|
||||
@@ -207,7 +205,7 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
|
||||
return switch (unsuccessfulTx.getProcessorResponseCode()) {
|
||||
case GENERIC_DECLINED_PROCESSOR_CODE, PAYPAL_FUNDING_INSTRUMENT_DECLINED_PROCESSOR_CODE ->
|
||||
CompletableFuture.failedFuture(
|
||||
new SubscriptionException.ProcessorException(getProvider(), createChargeFailure(unsuccessfulTx)));
|
||||
new SubscriptionProcessorException(getProvider(), createChargeFailure(unsuccessfulTx)));
|
||||
|
||||
default -> {
|
||||
logger.info("PayPal charge unexpectedly failed: {}", unsuccessfulTx.getProcessorResponseCode());
|
||||
@@ -317,130 +315,105 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<ProcessorCustomer> createCustomer(final byte[] subscriberUser, @Nullable final ClientPlatform clientPlatform) {
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
CustomerRequest request = new CustomerRequest()
|
||||
.customField("subscriber_user", HexFormat.of().formatHex(subscriberUser));
|
||||
public ProcessorCustomer createCustomer(final byte[] subscriberUser, @Nullable final ClientPlatform clientPlatform) {
|
||||
CustomerRequest request = new CustomerRequest()
|
||||
.customField("subscriber_user", HexFormat.of().formatHex(subscriberUser));
|
||||
|
||||
if (clientPlatform != null) {
|
||||
request.customField("client_platform", clientPlatform.name().toLowerCase());
|
||||
}
|
||||
|
||||
try {
|
||||
return braintreeGateway.customer().create(request);
|
||||
} catch (BraintreeException e) {
|
||||
throw new CompletionException(e);
|
||||
}
|
||||
}, executor)
|
||||
.thenApply(result -> {
|
||||
if (!result.isSuccess()) {
|
||||
throw new CompletionException(new BraintreeException(result.getMessage()));
|
||||
}
|
||||
|
||||
return new ProcessorCustomer(result.getTarget().getId(), PaymentProvider.BRAINTREE);
|
||||
});
|
||||
if (clientPlatform != null) {
|
||||
request.customField("client_platform", clientPlatform.name().toLowerCase());
|
||||
}
|
||||
|
||||
final Result<Customer> result = braintreeGateway.customer().create(request);
|
||||
if (!result.isSuccess()) {
|
||||
throw new BraintreeException(result.getMessage());
|
||||
}
|
||||
return new ProcessorCustomer(result.getTarget().getId(), PaymentProvider.BRAINTREE);
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<String> createPaymentMethodSetupToken(final String customerId) {
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
ClientTokenRequest request = new ClientTokenRequest()
|
||||
.customerId(customerId);
|
||||
public String createPaymentMethodSetupToken(final String customerId) {
|
||||
ClientTokenRequest request = new ClientTokenRequest().customerId(customerId);
|
||||
|
||||
return braintreeGateway.clientToken().generate(request);
|
||||
}, executor);
|
||||
return braintreeGateway.clientToken().generate(request);
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Void> setDefaultPaymentMethodForCustomer(String customerId, String billingAgreementToken,
|
||||
public void setDefaultPaymentMethodForCustomer(String customerId, String billingAgreementToken,
|
||||
@Nullable String currentSubscriptionId) {
|
||||
final Optional<String> maybeSubscriptionId = Optional.ofNullable(currentSubscriptionId);
|
||||
return braintreeGraphqlClient.tokenizePayPalBillingAgreement(billingAgreementToken)
|
||||
.thenCompose(tokenizePayPalBillingAgreement ->
|
||||
braintreeGraphqlClient.vaultPaymentMethod(customerId, tokenizePayPalBillingAgreement.paymentMethod.id))
|
||||
.thenApplyAsync(vaultPaymentMethod -> braintreeGateway.customer()
|
||||
.update(customerId, new CustomerRequest()
|
||||
.defaultPaymentMethodToken(vaultPaymentMethod.paymentMethod.id)),
|
||||
executor)
|
||||
.thenAcceptAsync(result -> {
|
||||
maybeSubscriptionId.ifPresent(
|
||||
subscriptionId -> braintreeGateway.subscription()
|
||||
.update(subscriptionId, new SubscriptionRequest()
|
||||
.paymentMethodToken(result.getTarget().getDefaultPaymentMethod().getToken())));
|
||||
}, executor);
|
||||
final TokenizePayPalBillingAgreementMutation.TokenizePayPalBillingAgreement tokenizePayPalBillingAgreement =
|
||||
braintreeGraphqlClient.tokenizePayPalBillingAgreement(billingAgreementToken).join();
|
||||
final VaultPaymentMethodMutation.VaultPaymentMethod vaultPaymentMethod =
|
||||
braintreeGraphqlClient.vaultPaymentMethod(customerId, tokenizePayPalBillingAgreement.paymentMethod.id).join();
|
||||
final Result<Customer> result = braintreeGateway.customer()
|
||||
.update(customerId, new CustomerRequest().defaultPaymentMethodToken(vaultPaymentMethod.paymentMethod.id));
|
||||
maybeSubscriptionId.ifPresent(subscriptionId ->
|
||||
braintreeGateway.subscription().update(subscriptionId, new SubscriptionRequest()
|
||||
.paymentMethodToken(result.getTarget().getDefaultPaymentMethod().getToken())));
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Object> getSubscription(String subscriptionId) {
|
||||
return CompletableFuture.supplyAsync(() -> braintreeGateway.subscription().find(subscriptionId), executor);
|
||||
public Object getSubscription(String subscriptionId) {
|
||||
return braintreeGateway.subscription().find(subscriptionId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<SubscriptionId> createSubscription(String customerId, String planId, long level,
|
||||
long lastSubscriptionCreatedAt) {
|
||||
public SubscriptionId createSubscription(String customerId, String planId, long level,
|
||||
long lastSubscriptionCreatedAt)
|
||||
throws SubscriptionProcessorConflictException, SubscriptionProcessorException {
|
||||
|
||||
return getDefaultPaymentMethod(customerId)
|
||||
.thenCompose(paymentMethod -> {
|
||||
if (paymentMethod == null) {
|
||||
throw ExceptionUtils.wrap(new SubscriptionException.ProcessorConflict());
|
||||
}
|
||||
final com.braintreegateway.PaymentMethod paymentMethod = getDefaultPaymentMethod(customerId);
|
||||
if (paymentMethod == null) {
|
||||
throw new SubscriptionProcessorConflictException();
|
||||
}
|
||||
|
||||
final Optional<Subscription> maybeExistingSubscription = paymentMethod.getSubscriptions().stream()
|
||||
.filter(sub -> sub.getStatus().equals(Subscription.Status.ACTIVE))
|
||||
.filter(Subscription::neverExpires)
|
||||
.findAny();
|
||||
final Optional<Subscription> maybeExistingSubscription = paymentMethod.getSubscriptions().stream()
|
||||
.filter(sub -> sub.getStatus().equals(Subscription.Status.ACTIVE))
|
||||
.filter(Subscription::neverExpires)
|
||||
.findAny();
|
||||
|
||||
return maybeExistingSubscription.map(subscription -> findPlan(subscription.getPlanId())
|
||||
.thenApply(plan -> {
|
||||
if (getLevelForPlan(plan) != level) {
|
||||
// if this happens, the likely cause is retrying an apparently failed request (likely some sort of timeout or network interruption)
|
||||
// with a different level.
|
||||
// In this case, it’s safer and easier to recover by returning this subscription, rather than
|
||||
// returning an error
|
||||
logger.warn("existing subscription had unexpected level");
|
||||
}
|
||||
return subscription;
|
||||
}))
|
||||
.orElseGet(() -> findPlan(planId).thenApplyAsync(plan -> {
|
||||
final Result<Subscription> result = braintreeGateway.subscription().create(new SubscriptionRequest()
|
||||
.planId(planId)
|
||||
.paymentMethodToken(paymentMethod.getToken())
|
||||
.merchantAccountId(
|
||||
currenciesToMerchantAccounts.get(plan.getCurrencyIsoCode().toLowerCase(Locale.ROOT)))
|
||||
.options()
|
||||
.startImmediately(true)
|
||||
.done()
|
||||
);
|
||||
if (maybeExistingSubscription.isPresent()) {
|
||||
final Subscription subscription = maybeExistingSubscription.get();
|
||||
final Plan plan = findPlan(subscription.getPlanId());
|
||||
if (getLevelForPlan(plan) != level) {
|
||||
// if this happens, the likely cause is retrying an apparently failed request (likely some sort of timeout or network interruption)
|
||||
// with a different level.
|
||||
// In this case, it’s safer and easier to recover by returning this subscription, rather than
|
||||
// returning an error
|
||||
logger.warn("existing subscription had unexpected level");
|
||||
}
|
||||
return new SubscriptionId(subscription.getId());
|
||||
}
|
||||
final Plan plan = findPlan(planId);
|
||||
final Result<Subscription> result = braintreeGateway.subscription().create(new SubscriptionRequest()
|
||||
.planId(planId)
|
||||
.paymentMethodToken(paymentMethod.getToken())
|
||||
.merchantAccountId(
|
||||
currenciesToMerchantAccounts.get(plan.getCurrencyIsoCode().toLowerCase(Locale.ROOT)))
|
||||
.options()
|
||||
.startImmediately(true)
|
||||
.done());
|
||||
|
||||
if (!result.isSuccess()) {
|
||||
final CompletionException completionException;
|
||||
if (result.getTarget() != null) {
|
||||
completionException = result.getTarget().getTransactions().stream().findFirst()
|
||||
.map(transaction -> new CompletionException(
|
||||
new SubscriptionException.ProcessorException(getProvider(), createChargeFailure(transaction))))
|
||||
.orElseGet(() -> new CompletionException(new BraintreeException(result.getMessage())));
|
||||
} else {
|
||||
completionException = new CompletionException(new BraintreeException(result.getMessage()));
|
||||
}
|
||||
if (!result.isSuccess()) {
|
||||
throw Optional
|
||||
.ofNullable(result.getTarget())
|
||||
.flatMap(subscription -> subscription.getTransactions().stream().findFirst())
|
||||
.map(transaction -> new SubscriptionProcessorException(getProvider(),
|
||||
createChargeFailure(transaction)))
|
||||
.orElseThrow(() -> new BraintreeException(result.getMessage()));
|
||||
}
|
||||
|
||||
throw completionException;
|
||||
}
|
||||
|
||||
return result.getTarget();
|
||||
}));
|
||||
}).thenApply(subscription -> new SubscriptionId(subscription.getId()));
|
||||
return new SubscriptionId(result.getTarget().getId());
|
||||
}
|
||||
|
||||
private CompletableFuture<com.braintreegateway.PaymentMethod> getDefaultPaymentMethod(String customerId) {
|
||||
return CompletableFuture.supplyAsync(() -> braintreeGateway.customer().find(customerId).getDefaultPaymentMethod(),
|
||||
executor);
|
||||
private com.braintreegateway.PaymentMethod getDefaultPaymentMethod(String customerId) {
|
||||
return braintreeGateway.customer().find(customerId).getDefaultPaymentMethod();
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public CompletableFuture<SubscriptionId> updateSubscription(Object subscriptionObj, String planId, long level,
|
||||
String idempotencyKey) {
|
||||
public CustomerAwareSubscriptionPaymentProcessor.SubscriptionId updateSubscription(Object subscriptionObj, String planId, long level,
|
||||
String idempotencyKey) throws SubscriptionProcessorConflictException, SubscriptionProcessorException {
|
||||
|
||||
if (!(subscriptionObj instanceof final Subscription subscription)) {
|
||||
throw new IllegalArgumentException("invalid subscription object: " + subscriptionObj.getClass().getName());
|
||||
@@ -449,31 +422,26 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
|
||||
// since badge redemption is untrackable by design and unrevokable, subscription changes must be immediate and
|
||||
// not prorated. Braintree subscriptions cannot change their next billing date,
|
||||
// so we must end the existing one and create a new one
|
||||
return endSubscription(subscription)
|
||||
.thenCompose(ignored -> {
|
||||
endSubscription(subscription);
|
||||
|
||||
final Transaction transaction = getLatestTransactionForSubscription(subscription)
|
||||
.orElseThrow(() -> ExceptionUtils.wrap(new SubscriptionException.ProcessorConflict()));
|
||||
final Transaction transaction = getLatestTransactionForSubscription(subscription)
|
||||
.orElseThrow(() -> ExceptionUtils.wrap(new SubscriptionProcessorConflictException()));
|
||||
|
||||
final Customer customer = transaction.getCustomer();
|
||||
final Customer customer = transaction.getCustomer();
|
||||
|
||||
return createSubscription(customer.getId(), planId, level,
|
||||
subscription.getCreatedAt().toInstant().getEpochSecond());
|
||||
});
|
||||
return createSubscription(customer.getId(), planId, level,
|
||||
subscription.getCreatedAt().toInstant().getEpochSecond());
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<LevelAndCurrency> getLevelAndCurrencyForSubscription(Object subscriptionObj) {
|
||||
public LevelAndCurrency getLevelAndCurrencyForSubscription(Object subscriptionObj) {
|
||||
final Subscription subscription = getSubscription(subscriptionObj);
|
||||
|
||||
return findPlan(subscription.getPlanId())
|
||||
.thenApply(
|
||||
plan -> new LevelAndCurrency(getLevelForPlan(plan), plan.getCurrencyIsoCode().toLowerCase(Locale.ROOT)));
|
||||
|
||||
final Plan plan = findPlan(subscription.getPlanId());
|
||||
return new LevelAndCurrency(getLevelForPlan(plan), plan.getCurrencyIsoCode().toLowerCase(Locale.ROOT));
|
||||
}
|
||||
|
||||
private CompletableFuture<Plan> findPlan(String planId) {
|
||||
return CompletableFuture.supplyAsync(() -> braintreeGateway.plan().find(planId), executor);
|
||||
private Plan findPlan(String planId) {
|
||||
return braintreeGateway.plan().find(planId);
|
||||
}
|
||||
|
||||
private long getLevelForPlan(final Plan plan) {
|
||||
@@ -489,37 +457,32 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<SubscriptionInformation> getSubscriptionInformation(final String subscriptionId) {
|
||||
return getSubscription(subscriptionId).thenApplyAsync(subscriptionObj -> {
|
||||
final Subscription subscription = getSubscription(subscriptionObj);
|
||||
public SubscriptionInformation getSubscriptionInformation(final String subscriptionId) {
|
||||
final Subscription subscription = getSubscription(getSubscription(subscriptionId));
|
||||
final Plan plan = braintreeGateway.plan().find(subscription.getPlanId());
|
||||
final long level = getLevelForPlan(plan);
|
||||
|
||||
final Plan plan = braintreeGateway.plan().find(subscription.getPlanId());
|
||||
final Instant anchor = subscription.getFirstBillingDate().toInstant();
|
||||
final Instant endOfCurrentPeriod = subscription.getBillingPeriodEndDate().toInstant();
|
||||
|
||||
final long level = getLevelForPlan(plan);
|
||||
final TransactionInfo latestTransactionInfo = getLatestTransactionForSubscription(subscription)
|
||||
.map(this::getTransactionInfo)
|
||||
.orElse(new TransactionInfo(PaymentMethod.PAYPAL, false, false, null));
|
||||
|
||||
final Instant anchor = subscription.getFirstBillingDate().toInstant();
|
||||
final Instant endOfCurrentPeriod = subscription.getBillingPeriodEndDate().toInstant();
|
||||
|
||||
final TransactionInfo latestTransactionInfo = getLatestTransactionForSubscription(subscription)
|
||||
.map(this::getTransactionInfo)
|
||||
.orElse(new TransactionInfo(PaymentMethod.PAYPAL, false, false, null));
|
||||
|
||||
return new SubscriptionInformation(
|
||||
new SubscriptionPrice(plan.getCurrencyIsoCode().toUpperCase(Locale.ROOT),
|
||||
SubscriptionCurrencyUtil.convertBraintreeAmountToApiAmount(plan.getCurrencyIsoCode(), plan.getPrice())),
|
||||
level,
|
||||
anchor,
|
||||
endOfCurrentPeriod,
|
||||
Subscription.Status.ACTIVE == subscription.getStatus(),
|
||||
!subscription.neverExpires(),
|
||||
getSubscriptionStatus(subscription.getStatus(), latestTransactionInfo.transactionFailed()),
|
||||
PaymentProvider.BRAINTREE,
|
||||
latestTransactionInfo.paymentMethod(),
|
||||
latestTransactionInfo.paymentProcessing(),
|
||||
latestTransactionInfo.chargeFailure()
|
||||
);
|
||||
|
||||
}, executor);
|
||||
return new SubscriptionInformation(
|
||||
new SubscriptionPrice(plan.getCurrencyIsoCode().toUpperCase(Locale.ROOT),
|
||||
SubscriptionCurrencyUtil.convertBraintreeAmountToApiAmount(plan.getCurrencyIsoCode(), plan.getPrice())),
|
||||
level,
|
||||
anchor,
|
||||
endOfCurrentPeriod,
|
||||
Subscription.Status.ACTIVE == subscription.getStatus(),
|
||||
!subscription.neverExpires(),
|
||||
getSubscriptionStatus(subscription.getStatus(), latestTransactionInfo.transactionFailed()),
|
||||
PaymentProvider.BRAINTREE,
|
||||
latestTransactionInfo.paymentMethod(),
|
||||
latestTransactionInfo.paymentProcessing(),
|
||||
latestTransactionInfo.chargeFailure()
|
||||
);
|
||||
}
|
||||
|
||||
private record TransactionInfo(
|
||||
@@ -576,76 +539,69 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Void> cancelAllActiveSubscriptions(String customerId) {
|
||||
|
||||
return CompletableFuture.supplyAsync(() -> braintreeGateway.customer().find(customerId), executor).thenCompose(customer -> {
|
||||
|
||||
final List<CompletableFuture<Void>> subscriptionCancelFutures = Optional.ofNullable(customer.getDefaultPaymentMethod())
|
||||
.map(com.braintreegateway.PaymentMethod::getSubscriptions)
|
||||
.orElse(Collections.emptyList())
|
||||
.stream()
|
||||
.map(this::endSubscription)
|
||||
.toList();
|
||||
|
||||
return CompletableFuture.allOf(subscriptionCancelFutures.toArray(new CompletableFuture[0]));
|
||||
});
|
||||
public void cancelAllActiveSubscriptions(String customerId) {
|
||||
final Customer customer = braintreeGateway.customer().find(customerId);
|
||||
ExecutorUtil.runAll(executor, Optional.ofNullable(customer.getDefaultPaymentMethod())
|
||||
.stream()
|
||||
.flatMap(paymentMethod -> paymentMethod.getSubscriptions().stream())
|
||||
.<Runnable>map(subscription -> () -> this.endSubscription(subscription))
|
||||
.toList());
|
||||
}
|
||||
|
||||
private CompletableFuture<Void> endSubscription(Subscription subscription) {
|
||||
private void endSubscription(Subscription subscription) {
|
||||
final boolean latestTransactionFailed = getLatestTransactionForSubscription(subscription)
|
||||
.map(this::getTransactionInfo)
|
||||
.map(TransactionInfo::transactionFailed)
|
||||
.orElse(false);
|
||||
return switch (getSubscriptionStatus(subscription.getStatus(), latestTransactionFailed)) {
|
||||
switch (getSubscriptionStatus(subscription.getStatus(), latestTransactionFailed)) {
|
||||
// The payment for this period has not processed yet, we should immediately cancel to prevent any payment from
|
||||
// going through.
|
||||
case INCOMPLETE, PAST_DUE, UNPAID -> cancelSubscriptionImmediately(subscription);
|
||||
// Otherwise, set the subscription to cancel at the current period end. If the subscription is active, it may
|
||||
// continue to be used until the end of the period.
|
||||
default -> cancelSubscriptionAtEndOfCurrentPeriod(subscription);
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
private CompletableFuture<Void> cancelSubscriptionAtEndOfCurrentPeriod(Subscription subscription) {
|
||||
return CompletableFuture.runAsync(() -> braintreeGateway
|
||||
private void cancelSubscriptionAtEndOfCurrentPeriod(Subscription subscription) {
|
||||
braintreeGateway
|
||||
.subscription()
|
||||
.update(subscription.getId(),
|
||||
new SubscriptionRequest().numberOfBillingCycles(subscription.getCurrentBillingCycle())), executor);
|
||||
new SubscriptionRequest().numberOfBillingCycles(subscription.getCurrentBillingCycle()));
|
||||
}
|
||||
|
||||
private CompletableFuture<Void> cancelSubscriptionImmediately(Subscription subscription) {
|
||||
return CompletableFuture.runAsync(() -> braintreeGateway.subscription().cancel(subscription.getId()), executor);
|
||||
private void cancelSubscriptionImmediately(Subscription subscription) {
|
||||
braintreeGateway.subscription().cancel(subscription.getId());
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public CompletableFuture<ReceiptItem> getReceiptItem(String subscriptionId) {
|
||||
return getSubscription(subscriptionId)
|
||||
.thenApply(BraintreeManager::getSubscription)
|
||||
.thenApply(subscription -> getLatestTransactionForSubscription(subscription)
|
||||
.map(transaction -> {
|
||||
if (!getPaymentStatus(transaction.getStatus()).equals(PaymentStatus.SUCCEEDED)) {
|
||||
final SubscriptionStatus subscriptionStatus = getSubscriptionStatus(subscription.getStatus(), true);
|
||||
if (subscriptionStatus.equals(SubscriptionStatus.ACTIVE) || subscriptionStatus.equals(SubscriptionStatus.PAST_DUE)) {
|
||||
throw ExceptionUtils.wrap(new SubscriptionException.ReceiptRequestedForOpenPayment());
|
||||
}
|
||||
throw ExceptionUtils.wrap(new SubscriptionException.ChargeFailurePaymentRequired(getProvider(), createChargeFailure(transaction)));
|
||||
}
|
||||
public ReceiptItem getReceiptItem(String subscriptionId)
|
||||
throws SubscriptionReceiptRequestedForOpenPaymentException, SubscriptionChargeFailurePaymentRequiredException {
|
||||
final Subscription subscription = getSubscription(getSubscription(subscriptionId));
|
||||
final Transaction transaction = getLatestTransactionForSubscription(subscription)
|
||||
.orElseThrow(SubscriptionReceiptRequestedForOpenPaymentException::new);
|
||||
if (!getPaymentStatus(transaction.getStatus()).equals(PaymentStatus.SUCCEEDED)) {
|
||||
final SubscriptionStatus subscriptionStatus = getSubscriptionStatus(subscription.getStatus(), true);
|
||||
if (subscriptionStatus.equals(SubscriptionStatus.ACTIVE) || subscriptionStatus.equals(
|
||||
SubscriptionStatus.PAST_DUE)) {
|
||||
throw new SubscriptionReceiptRequestedForOpenPaymentException();
|
||||
}
|
||||
throw new SubscriptionChargeFailurePaymentRequiredException(getProvider(), createChargeFailure(transaction));
|
||||
}
|
||||
|
||||
final Instant paidAt = transaction.getSubscriptionDetails().getBillingPeriodStartDate().toInstant();
|
||||
final Plan plan = braintreeGateway.plan().find(transaction.getPlanId());
|
||||
final Instant paidAt = transaction.getSubscriptionDetails().getBillingPeriodStartDate().toInstant();
|
||||
final Plan plan = braintreeGateway.plan().find(transaction.getPlanId());
|
||||
|
||||
final BraintreePlanMetadata metadata;
|
||||
try {
|
||||
metadata = SystemMapper.jsonMapper().readValue(plan.getDescription(), BraintreePlanMetadata.class);
|
||||
final BraintreePlanMetadata metadata;
|
||||
try {
|
||||
metadata = SystemMapper.jsonMapper().readValue(plan.getDescription(), BraintreePlanMetadata.class);
|
||||
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
return new ReceiptItem(transaction.getId(), PaymentTime.periodStart(paidAt), metadata.level());
|
||||
})
|
||||
.orElseThrow(() -> ExceptionUtils.wrap(new SubscriptionException.ReceiptRequestedForOpenPayment())));
|
||||
return new ReceiptItem(transaction.getId(), PaymentTime.periodStart(paidAt), metadata.level());
|
||||
}
|
||||
|
||||
private static Subscription getSubscription(Object subscriptionObj) {
|
||||
|
||||
+52
-14
@@ -6,7 +6,6 @@
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import javax.annotation.Nullable;
|
||||
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
|
||||
|
||||
@@ -22,33 +21,72 @@ public interface CustomerAwareSubscriptionPaymentProcessor extends SubscriptionP
|
||||
|
||||
Set<String> getSupportedCurrenciesForPaymentMethod(PaymentMethod paymentMethod);
|
||||
|
||||
CompletableFuture<ProcessorCustomer> createCustomer(byte[] subscriberUser, @Nullable ClientPlatform clientPlatform);
|
||||
/**
|
||||
* Create a customer on the payment processor
|
||||
*
|
||||
* @param subscriberUser An identifier that will be stored with the customer
|
||||
* @param clientPlatform The {@link ClientPlatform} of the requesting client
|
||||
* @return A {@link ProcessorCustomer} that can be used to identify this customer on the provider
|
||||
*/
|
||||
ProcessorCustomer createCustomer(byte[] subscriberUser, @Nullable ClientPlatform clientPlatform);
|
||||
|
||||
CompletableFuture<String> createPaymentMethodSetupToken(String customerId);
|
||||
String createPaymentMethodSetupToken(String customerId);
|
||||
|
||||
|
||||
/**
|
||||
* @param customerId
|
||||
* @param paymentMethodToken a processor-specific token necessary
|
||||
* Set a default payment method
|
||||
*
|
||||
* @param customerId The customer to add a default payment method to
|
||||
* @param paymentMethodToken a processor-specific token previously acquired at
|
||||
* {@link #createPaymentMethodSetupToken}
|
||||
* @param currentSubscriptionId (nullable) an active subscription ID, in case it needs an explicit update
|
||||
* @return
|
||||
* @throws SubscriptionInvalidArgumentsException If the paymentMethodToken is invalid or the payment method has not
|
||||
* finished being set up
|
||||
*/
|
||||
CompletableFuture<Void> setDefaultPaymentMethodForCustomer(String customerId, String paymentMethodToken,
|
||||
@Nullable String currentSubscriptionId);
|
||||
void setDefaultPaymentMethodForCustomer(String customerId, String paymentMethodToken,
|
||||
@Nullable String currentSubscriptionId) throws SubscriptionInvalidArgumentsException;
|
||||
|
||||
CompletableFuture<Object> getSubscription(String subscriptionId);
|
||||
Object getSubscription(String subscriptionId);
|
||||
|
||||
CompletableFuture<SubscriptionId> createSubscription(String customerId, String templateId, long level,
|
||||
long lastSubscriptionCreatedAt);
|
||||
/**
|
||||
* Create a subscription on a customer
|
||||
*
|
||||
* @param customerId The customer to create the subscription on
|
||||
* @param templateId An identifier for the type of subscription to create
|
||||
* @param level The level of the subscription
|
||||
* @param lastSubscriptionCreatedAt The timestamp of the last successfully created subscription
|
||||
* @return A subscription identifier
|
||||
* @throws SubscriptionProcessorException If there was a failure processing the charge
|
||||
* @throws SubscriptionInvalidArgumentsException If there was a failure because an idempotency key was reused on a
|
||||
* modified request, or if the payment requires additional steps
|
||||
* before charging
|
||||
* @throws SubscriptionProcessorConflictException If there was no payment method on the customer
|
||||
*/
|
||||
SubscriptionId createSubscription(String customerId, String templateId, long level, long lastSubscriptionCreatedAt)
|
||||
throws SubscriptionProcessorException, SubscriptionInvalidArgumentsException, SubscriptionProcessorConflictException;
|
||||
|
||||
CompletableFuture<SubscriptionId> updateSubscription(
|
||||
Object subscription, String templateId, long level, String idempotencyKey);
|
||||
/**
|
||||
* Update an existing subscription on a customer
|
||||
*
|
||||
* @param subscription The subscription to update
|
||||
* @param templateId An identifier for the new subscription type
|
||||
* @param level The target level of the subscription
|
||||
* @param idempotencyKey An idempotency key to prevent retries of successful requests
|
||||
* @return A subscription identifier
|
||||
* @throws SubscriptionProcessorException If there was a failure processing the charge
|
||||
* @throws SubscriptionInvalidArgumentsException If there was a failure because an idempotency key was reused on a
|
||||
* modified request, or if the payment requires additional steps
|
||||
* before charging
|
||||
* @throws SubscriptionProcessorConflictException If there was no payment method on the customer
|
||||
*/
|
||||
SubscriptionId updateSubscription(Object subscription, String templateId, long level, String idempotencyKey)
|
||||
throws SubscriptionInvalidArgumentsException, SubscriptionProcessorException, SubscriptionProcessorConflictException;
|
||||
|
||||
/**
|
||||
* @param subscription
|
||||
* @return the subscription’s current level and lower-case currency code
|
||||
*/
|
||||
CompletableFuture<LevelAndCurrency> getLevelAndCurrencyForSubscription(Object subscription);
|
||||
LevelAndCurrency getLevelAndCurrencyForSubscription(Object subscription);
|
||||
|
||||
record SubscriptionId(String id) {
|
||||
|
||||
|
||||
+155
-168
@@ -16,6 +16,7 @@ import com.google.api.services.androidpublisher.model.AutoRenewingPlan;
|
||||
import com.google.api.services.androidpublisher.model.BasePlan;
|
||||
import com.google.api.services.androidpublisher.model.OfferDetails;
|
||||
import com.google.api.services.androidpublisher.model.RegionalBasePlanConfig;
|
||||
import com.google.api.services.androidpublisher.model.Subscription;
|
||||
import com.google.api.services.androidpublisher.model.SubscriptionPurchaseLineItem;
|
||||
import com.google.api.services.androidpublisher.model.SubscriptionPurchaseV2;
|
||||
import com.google.api.services.androidpublisher.model.SubscriptionPurchasesAcknowledgeRequest;
|
||||
@@ -27,6 +28,7 @@ import io.micrometer.core.instrument.Tags;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.security.GeneralSecurityException;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
@@ -37,8 +39,6 @@ import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.stream.Collectors;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
@@ -46,8 +46,6 @@ import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.PaymentTime;
|
||||
import org.whispersystems.textsecuregcm.storage.SubscriptionException;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
|
||||
/**
|
||||
* Manages subscriptions made with the Play Billing API
|
||||
@@ -66,7 +64,6 @@ public class GooglePlayBillingManager implements SubscriptionPaymentProcessor {
|
||||
private static final Logger logger = LoggerFactory.getLogger(GooglePlayBillingManager.class);
|
||||
|
||||
private final AndroidPublisher androidPublisher;
|
||||
private final Executor executor;
|
||||
private final String packageName;
|
||||
private final Map<String, Long> productIdToLevel;
|
||||
private final Clock clock;
|
||||
@@ -80,8 +77,7 @@ public class GooglePlayBillingManager implements SubscriptionPaymentProcessor {
|
||||
final InputStream credentialsStream,
|
||||
final String packageName,
|
||||
final String applicationName,
|
||||
final Map<String, Long> productIdToLevel,
|
||||
final Executor executor)
|
||||
final Map<String, Long> productIdToLevel)
|
||||
throws GeneralSecurityException, IOException {
|
||||
this(new AndroidPublisher.Builder(
|
||||
GoogleNetHttpTransport.newTrustedTransport(),
|
||||
@@ -91,7 +87,7 @@ public class GooglePlayBillingManager implements SubscriptionPaymentProcessor {
|
||||
.createScoped(AndroidPublisherScopes.ANDROIDPUBLISHER)))
|
||||
.setApplicationName(applicationName)
|
||||
.build(),
|
||||
Clock.systemUTC(), packageName, productIdToLevel, executor);
|
||||
Clock.systemUTC(), packageName, productIdToLevel);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
@@ -99,12 +95,10 @@ public class GooglePlayBillingManager implements SubscriptionPaymentProcessor {
|
||||
final AndroidPublisher androidPublisher,
|
||||
final Clock clock,
|
||||
final String packageName,
|
||||
final Map<String, Long> productIdToLevel,
|
||||
final Executor executor) {
|
||||
final Map<String, Long> productIdToLevel) {
|
||||
this.clock = clock;
|
||||
this.androidPublisher = androidPublisher;
|
||||
this.productIdToLevel = productIdToLevel;
|
||||
this.executor = Objects.requireNonNull(executor);
|
||||
this.packageName = packageName;
|
||||
}
|
||||
|
||||
@@ -138,12 +132,13 @@ public class GooglePlayBillingManager implements SubscriptionPaymentProcessor {
|
||||
*
|
||||
* @return A stage that completes when the purchase has been successfully acknowledged
|
||||
*/
|
||||
public CompletableFuture<Void> acknowledgePurchase() {
|
||||
public void acknowledgePurchase()
|
||||
throws RateLimitExceededException, SubscriptionNotFoundException {
|
||||
if (!requiresAck) {
|
||||
// We've already acknowledged this purchase on a previous attempt, nothing to do
|
||||
return CompletableFuture.completedFuture(null);
|
||||
return;
|
||||
}
|
||||
return executeTokenOperation(pub -> pub.purchases().subscriptions()
|
||||
executeTokenOperation(pub -> pub.purchases().subscriptions()
|
||||
.acknowledge(packageName, productId, purchaseToken, new SubscriptionPurchasesAcknowledgeRequest()));
|
||||
}
|
||||
|
||||
@@ -157,45 +152,47 @@ public class GooglePlayBillingManager implements SubscriptionPaymentProcessor {
|
||||
* then acknowledged with {@link ValidatedToken#acknowledgePurchase()}
|
||||
*
|
||||
* @param purchaseToken The play store billing purchaseToken that represents a subscription purchase
|
||||
* @return A stage that completes successfully when the token has been validated, or fails if the token does not
|
||||
* represent an active purchase
|
||||
* @return A {@link ValidatedToken} that can be acknowledged
|
||||
* @throws RateLimitExceededException If rate-limited by play-billing
|
||||
* @throws SubscriptionNotFoundException If the provided purchaseToken was not found in play-billing
|
||||
* @throws SubscriptionPaymentRequiredException If the purchaseToken exists but is in a state that does not grant the
|
||||
* user an entitlement
|
||||
*/
|
||||
public CompletableFuture<ValidatedToken> validateToken(String purchaseToken) {
|
||||
return lookupSubscription(purchaseToken).thenApplyAsync(subscription -> {
|
||||
public ValidatedToken validateToken(String purchaseToken)
|
||||
throws RateLimitExceededException, SubscriptionNotFoundException, SubscriptionPaymentRequiredException {
|
||||
final SubscriptionPurchaseV2 subscription = lookupSubscription(purchaseToken);
|
||||
final SubscriptionState state = SubscriptionState
|
||||
.fromString(subscription.getSubscriptionState())
|
||||
.orElse(SubscriptionState.UNSPECIFIED);
|
||||
|
||||
final SubscriptionState state = SubscriptionState
|
||||
.fromString(subscription.getSubscriptionState())
|
||||
.orElse(SubscriptionState.UNSPECIFIED);
|
||||
Metrics.counter(VALIDATE_COUNTER_NAME, subscriptionTags(subscription)).increment();
|
||||
|
||||
Metrics.counter(VALIDATE_COUNTER_NAME, subscriptionTags(subscription)).increment();
|
||||
// We only accept tokens in a state where the user may be entitled to their purchase. This is true even in the
|
||||
// CANCELLED state. For example, a user may subscribe for 1 month, then immediately cancel (disabling auto-renew)
|
||||
// and then submit their token. In this case they should still be able to retrieve their entitlement.
|
||||
// See https://developer.android.com/google/play/billing/integrate#life
|
||||
if (state != SubscriptionState.ACTIVE
|
||||
&& state != SubscriptionState.IN_GRACE_PERIOD
|
||||
&& state != SubscriptionState.CANCELED) {
|
||||
throw new SubscriptionPaymentRequiredException(
|
||||
"Cannot acknowledge purchase for subscription in state " + subscription.getSubscriptionState());
|
||||
}
|
||||
|
||||
// We only accept tokens in a state where the user may be entitled to their purchase. This is true even in the
|
||||
// CANCELLED state. For example, a user may subscribe for 1 month, then immediately cancel (disabling auto-renew)
|
||||
// and then submit their token. In this case they should still be able to retrieve their entitlement.
|
||||
// See https://developer.android.com/google/play/billing/integrate#life
|
||||
if (state != SubscriptionState.ACTIVE
|
||||
&& state != SubscriptionState.IN_GRACE_PERIOD
|
||||
&& state != SubscriptionState.CANCELED) {
|
||||
throw ExceptionUtils.wrap(new SubscriptionException.PaymentRequired(
|
||||
"Cannot acknowledge purchase for subscription in state " + subscription.getSubscriptionState()));
|
||||
}
|
||||
final AcknowledgementState acknowledgementState = AcknowledgementState
|
||||
.fromString(subscription.getAcknowledgementState())
|
||||
.orElse(AcknowledgementState.UNSPECIFIED);
|
||||
|
||||
final AcknowledgementState acknowledgementState = AcknowledgementState
|
||||
.fromString(subscription.getAcknowledgementState())
|
||||
.orElse(AcknowledgementState.UNSPECIFIED);
|
||||
final boolean requiresAck = switch (acknowledgementState) {
|
||||
case ACKNOWLEDGED -> false;
|
||||
case PENDING -> true;
|
||||
case UNSPECIFIED -> throw new UncheckedIOException(
|
||||
new IOException("Invalid acknowledgement state " + subscription.getAcknowledgementState()));
|
||||
};
|
||||
|
||||
final boolean requiresAck = switch (acknowledgementState) {
|
||||
case ACKNOWLEDGED -> false;
|
||||
case PENDING -> true;
|
||||
case UNSPECIFIED -> throw ExceptionUtils.wrap(
|
||||
new IOException("Invalid acknowledgement state " + subscription.getAcknowledgementState()));
|
||||
};
|
||||
final SubscriptionPurchaseLineItem purchase = getLineItem(subscription);
|
||||
final long level = productIdToLevel(purchase.getProductId());
|
||||
|
||||
final SubscriptionPurchaseLineItem purchase = getLineItem(subscription);
|
||||
final long level = productIdToLevel(purchase.getProductId());
|
||||
|
||||
return new ValidatedToken(level, purchase.getProductId(), purchaseToken, requiresAck);
|
||||
}, executor);
|
||||
return new ValidatedToken(level, purchase.getProductId(), purchaseToken, requiresAck);
|
||||
}
|
||||
|
||||
|
||||
@@ -204,10 +201,11 @@ public class GooglePlayBillingManager implements SubscriptionPaymentProcessor {
|
||||
* entitlement until their current period expires.
|
||||
*
|
||||
* @param purchaseToken The purchaseToken associated with the subscription
|
||||
* @return A stage that completes when the subscription has successfully been cancelled
|
||||
* @throws RateLimitExceededException If rate-limited by play-billing
|
||||
*/
|
||||
public CompletableFuture<Void> cancelAllActiveSubscriptions(String purchaseToken) {
|
||||
return lookupSubscription(purchaseToken).thenCompose(subscription -> {
|
||||
public void cancelAllActiveSubscriptions(String purchaseToken) throws RateLimitExceededException {
|
||||
try {
|
||||
final SubscriptionPurchaseV2 subscription = lookupSubscription(purchaseToken);
|
||||
Metrics.counter(CANCEL_COUNTER_NAME, subscriptionTags(subscription)).increment();
|
||||
|
||||
final SubscriptionState state = SubscriptionState
|
||||
@@ -216,118 +214,119 @@ public class GooglePlayBillingManager implements SubscriptionPaymentProcessor {
|
||||
|
||||
if (state == SubscriptionState.CANCELED || state == SubscriptionState.EXPIRED) {
|
||||
// already cancelled, nothing to do
|
||||
return CompletableFuture.completedFuture(null);
|
||||
return;
|
||||
}
|
||||
final SubscriptionPurchaseLineItem purchase = getLineItem(subscription);
|
||||
|
||||
return executeTokenOperation(pub ->
|
||||
executeTokenOperation(pub ->
|
||||
pub.purchases().subscriptions().cancel(packageName, purchase.getProductId(), purchaseToken));
|
||||
})
|
||||
// If the subscription is not found, no need to do anything
|
||||
.exceptionally(ExceptionUtils.exceptionallyHandler(SubscriptionException.NotFound.class, e -> null));
|
||||
} catch (SubscriptionNotFoundException e) {
|
||||
// If the subscription is not found there is no need to do anything, so we can squash it
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<SubscriptionInformation> getSubscriptionInformation(final String purchaseToken) {
|
||||
public SubscriptionInformation getSubscriptionInformation(final String purchaseToken)
|
||||
throws RateLimitExceededException, SubscriptionNotFoundException {
|
||||
|
||||
final CompletableFuture<SubscriptionPurchaseV2> subscriptionFuture = lookupSubscription(purchaseToken);
|
||||
final CompletableFuture<SubscriptionPrice> priceFuture = subscriptionFuture.thenCompose(this::getSubscriptionPrice);
|
||||
final SubscriptionPurchaseV2 subscription = lookupSubscription(purchaseToken);
|
||||
final SubscriptionPrice price = getSubscriptionPrice(subscription);
|
||||
|
||||
return subscriptionFuture.thenCombineAsync(priceFuture, (subscription, price) -> {
|
||||
final SubscriptionPurchaseLineItem lineItem = getLineItem(subscription);
|
||||
final Optional<Instant> billingCycleAnchor = getStartTime(subscription);
|
||||
final Optional<Instant> expiration = getExpiration(lineItem);
|
||||
|
||||
final SubscriptionPurchaseLineItem lineItem = getLineItem(subscription);
|
||||
final Optional<Instant> billingCycleAnchor = getStartTime(subscription);
|
||||
final Optional<Instant> expiration = getExpiration(lineItem);
|
||||
final SubscriptionStatus status = switch (SubscriptionState
|
||||
.fromString(subscription.getSubscriptionState())
|
||||
.orElse(SubscriptionState.UNSPECIFIED)) {
|
||||
// In play terminology CANCELLED is the same as an active subscription with cancelAtPeriodEnd set in Stripe. So
|
||||
// it should map to the ACTIVE stripe status.
|
||||
case ACTIVE, CANCELED -> SubscriptionStatus.ACTIVE;
|
||||
case PENDING -> SubscriptionStatus.INCOMPLETE;
|
||||
case ON_HOLD, PAUSED -> SubscriptionStatus.PAST_DUE;
|
||||
case IN_GRACE_PERIOD -> SubscriptionStatus.UNPAID;
|
||||
// EXPIRED is the equivalent of a Stripe CANCELLED subscription
|
||||
case EXPIRED, PENDING_PURCHASE_CANCELED -> SubscriptionStatus.CANCELED;
|
||||
case UNSPECIFIED -> SubscriptionStatus.UNKNOWN;
|
||||
};
|
||||
|
||||
final SubscriptionStatus status = switch (SubscriptionState
|
||||
.fromString(subscription.getSubscriptionState())
|
||||
.orElse(SubscriptionState.UNSPECIFIED)) {
|
||||
// In play terminology CANCELLED is the same as an active subscription with cancelAtPeriodEnd set in Stripe. So
|
||||
// it should map to the ACTIVE stripe status.
|
||||
case ACTIVE, CANCELED -> SubscriptionStatus.ACTIVE;
|
||||
case PENDING -> SubscriptionStatus.INCOMPLETE;
|
||||
case ON_HOLD, PAUSED -> SubscriptionStatus.PAST_DUE;
|
||||
case IN_GRACE_PERIOD -> SubscriptionStatus.UNPAID;
|
||||
// EXPIRED is the equivalent of a Stripe CANCELLED subscription
|
||||
case EXPIRED, PENDING_PURCHASE_CANCELED -> SubscriptionStatus.CANCELED;
|
||||
case UNSPECIFIED -> SubscriptionStatus.UNKNOWN;
|
||||
};
|
||||
|
||||
final boolean autoRenewEnabled = Optional
|
||||
.ofNullable(lineItem.getAutoRenewingPlan())
|
||||
.map(AutoRenewingPlan::getAutoRenewEnabled) // returns null or false if auto-renew disabled
|
||||
.orElse(false);
|
||||
return new SubscriptionInformation(
|
||||
price,
|
||||
productIdToLevel(lineItem.getProductId()),
|
||||
billingCycleAnchor.orElse(null),
|
||||
expiration.orElse(null),
|
||||
expiration.map(clock.instant()::isBefore).orElse(false),
|
||||
!autoRenewEnabled,
|
||||
status,
|
||||
PaymentProvider.GOOGLE_PLAY_BILLING,
|
||||
PaymentMethod.GOOGLE_PLAY_BILLING,
|
||||
false,
|
||||
null);
|
||||
}, executor);
|
||||
final boolean autoRenewEnabled = Optional
|
||||
.ofNullable(lineItem.getAutoRenewingPlan())
|
||||
.map(AutoRenewingPlan::getAutoRenewEnabled) // returns null or false if auto-renew disabled
|
||||
.orElse(false);
|
||||
return new SubscriptionInformation(
|
||||
price,
|
||||
productIdToLevel(lineItem.getProductId()),
|
||||
billingCycleAnchor.orElse(null),
|
||||
expiration.orElse(null),
|
||||
expiration.map(clock.instant()::isBefore).orElse(false),
|
||||
!autoRenewEnabled,
|
||||
status,
|
||||
PaymentProvider.GOOGLE_PLAY_BILLING,
|
||||
PaymentMethod.GOOGLE_PLAY_BILLING,
|
||||
false,
|
||||
null);
|
||||
}
|
||||
|
||||
private CompletableFuture<SubscriptionPrice> getSubscriptionPrice(final SubscriptionPurchaseV2 subscriptionPurchase) {
|
||||
private SubscriptionPrice getSubscriptionPrice(final SubscriptionPurchaseV2 subscriptionPurchase) {
|
||||
|
||||
final SubscriptionPurchaseLineItem lineItem = getLineItem(subscriptionPurchase);
|
||||
final OfferDetails offerDetails = lineItem.getOfferDetails();
|
||||
final String basePlanId = offerDetails.getBasePlanId();
|
||||
|
||||
return this.executeAsync(pub -> pub.monetization().subscriptions().get(packageName, lineItem.getProductId()))
|
||||
.thenApplyAsync(subscription -> {
|
||||
try {
|
||||
final Subscription subscription = this.androidPublisher.monetization().subscriptions()
|
||||
.get(packageName, lineItem.getProductId()).execute();
|
||||
|
||||
final BasePlan basePlan = subscription.getBasePlans().stream()
|
||||
.filter(bp -> bp.getBasePlanId().equals(basePlanId))
|
||||
.findFirst()
|
||||
.orElseThrow(() -> ExceptionUtils.wrap(new IOException("unknown basePlanId " + basePlanId)));
|
||||
final String region = subscriptionPurchase.getRegionCode();
|
||||
final RegionalBasePlanConfig basePlanConfig = basePlan.getRegionalConfigs()
|
||||
.stream()
|
||||
.filter(rbpc -> Objects.equals(region, rbpc.getRegionCode()))
|
||||
.findFirst()
|
||||
.orElseThrow(() -> ExceptionUtils.wrap(new IOException("unknown subscription region " + region)));
|
||||
final BasePlan basePlan = subscription.getBasePlans().stream()
|
||||
.filter(bp -> bp.getBasePlanId().equals(basePlanId))
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new UncheckedIOException(new IOException("unknown basePlanId " + basePlanId)));
|
||||
final String region = subscriptionPurchase.getRegionCode();
|
||||
final RegionalBasePlanConfig basePlanConfig = basePlan.getRegionalConfigs()
|
||||
.stream()
|
||||
.filter(rbpc -> Objects.equals(region, rbpc.getRegionCode()))
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new UncheckedIOException(new IOException("unknown subscription region " + region)));
|
||||
|
||||
return new SubscriptionPrice(
|
||||
basePlanConfig.getPrice().getCurrencyCode().toUpperCase(Locale.ROOT),
|
||||
SubscriptionCurrencyUtil.convertGoogleMoneyToApiAmount(basePlanConfig.getPrice()));
|
||||
}, executor);
|
||||
return new SubscriptionPrice(
|
||||
basePlanConfig.getPrice().getCurrencyCode().toUpperCase(Locale.ROOT),
|
||||
SubscriptionCurrencyUtil.convertGoogleMoneyToApiAmount(basePlanConfig.getPrice()));
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<ReceiptItem> getReceiptItem(String purchaseToken) {
|
||||
return lookupSubscription(purchaseToken).thenApplyAsync(subscription -> {
|
||||
final AcknowledgementState acknowledgementState = AcknowledgementState
|
||||
.fromString(subscription.getAcknowledgementState())
|
||||
.orElse(AcknowledgementState.UNSPECIFIED);
|
||||
if (acknowledgementState != AcknowledgementState.ACKNOWLEDGED) {
|
||||
// We should only ever generate receipts for a stored and acknowledged token.
|
||||
logger.error("Tried to fetch receipt for purchaseToken {} that was never acknowledged", purchaseToken);
|
||||
throw new IllegalStateException("Tried to fetch receipt for purchaseToken that was never acknowledged");
|
||||
}
|
||||
public ReceiptItem getReceiptItem(String purchaseToken)
|
||||
throws RateLimitExceededException, SubscriptionNotFoundException, SubscriptionPaymentRequiredException {
|
||||
final SubscriptionPurchaseV2 subscription = lookupSubscription(purchaseToken);
|
||||
final AcknowledgementState acknowledgementState = AcknowledgementState
|
||||
.fromString(subscription.getAcknowledgementState())
|
||||
.orElse(AcknowledgementState.UNSPECIFIED);
|
||||
if (acknowledgementState != AcknowledgementState.ACKNOWLEDGED) {
|
||||
// We should only ever generate receipts for a stored and acknowledged token.
|
||||
logger.error("Tried to fetch receipt for purchaseToken {} that was never acknowledged", purchaseToken);
|
||||
throw new IllegalStateException("Tried to fetch receipt for purchaseToken that was never acknowledged");
|
||||
}
|
||||
|
||||
Metrics.counter(GET_RECEIPT_COUNTER_NAME, subscriptionTags(subscription)).increment();
|
||||
Metrics.counter(GET_RECEIPT_COUNTER_NAME, subscriptionTags(subscription)).increment();
|
||||
|
||||
final SubscriptionPurchaseLineItem purchase = getLineItem(subscription);
|
||||
final Instant expiration = getExpiration(purchase)
|
||||
.orElseThrow(() -> ExceptionUtils.wrap(new IOException("Invalid subscription expiration")));
|
||||
final SubscriptionPurchaseLineItem purchase = getLineItem(subscription);
|
||||
final Instant expiration = getExpiration(purchase)
|
||||
.orElseThrow(() -> new UncheckedIOException(new IOException("Invalid subscription expiration")));
|
||||
|
||||
if (expiration.isBefore(clock.instant())) {
|
||||
// We don't need to check any state at this point, just whether the subscription is currently valid. If the
|
||||
// subscription is in a grace period, the expiration time will be dynamically extended, see
|
||||
// https://developer.android.com/google/play/billing/lifecycle/subscriptions#grace-period
|
||||
throw ExceptionUtils.wrap(new SubscriptionException.PaymentRequired());
|
||||
}
|
||||
if (expiration.isBefore(clock.instant())) {
|
||||
// We don't need to check any state at this point, just whether the subscription is currently valid. If the
|
||||
// subscription is in a grace period, the expiration time will be dynamically extended, see
|
||||
// https://developer.android.com/google/play/billing/lifecycle/subscriptions#grace-period
|
||||
throw new SubscriptionPaymentRequiredException();
|
||||
}
|
||||
|
||||
return new ReceiptItem(
|
||||
subscription.getLatestOrderId(),
|
||||
PaymentTime.periodEnds(expiration),
|
||||
productIdToLevel(purchase.getProductId()));
|
||||
}, executor);
|
||||
return new ReceiptItem(
|
||||
subscription.getLatestOrderId(),
|
||||
PaymentTime.periodEnds(expiration),
|
||||
productIdToLevel(purchase.getProductId()));
|
||||
}
|
||||
|
||||
|
||||
@@ -336,23 +335,6 @@ public class GooglePlayBillingManager implements SubscriptionPaymentProcessor {
|
||||
AndroidPublisherRequest<T> req(AndroidPublisher publisher) throws IOException;
|
||||
}
|
||||
|
||||
/**
|
||||
* Asynchronously execute a synchronous API call from an AndroidPublisher
|
||||
*
|
||||
* @param apiCall A function that takes the publisher and returns the API call to execute
|
||||
* @param <R> The return type of the executed ApiCall
|
||||
* @return A stage that completes with the result of the API call
|
||||
*/
|
||||
private <R> CompletableFuture<R> executeAsync(final ApiCall<R> apiCall) {
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
try {
|
||||
return apiCall.req(androidPublisher).execute();
|
||||
} catch (IOException e) {
|
||||
throw ExceptionUtils.wrap(e);
|
||||
}
|
||||
}, executor);
|
||||
}
|
||||
|
||||
/**
|
||||
* Asynchronously execute a synchronous API call on a purchaseToken, mapping expected errors to the appropriate
|
||||
* {@link SubscriptionException}
|
||||
@@ -361,26 +343,31 @@ public class GooglePlayBillingManager implements SubscriptionPaymentProcessor {
|
||||
* @param <R> The result of the API call
|
||||
* @return A stage that completes with the result of the API call
|
||||
*/
|
||||
private <R> CompletableFuture<R> executeTokenOperation(final ApiCall<R> apiCall) {
|
||||
return executeAsync(apiCall)
|
||||
.exceptionally(ExceptionUtils.exceptionallyHandler(HttpResponseException.class, e -> {
|
||||
if (e.getStatusCode() == Response.Status.NOT_FOUND.getStatusCode()
|
||||
|| e.getStatusCode() == Response.Status.GONE.getStatusCode()) {
|
||||
throw ExceptionUtils.wrap(new SubscriptionException.NotFound());
|
||||
}
|
||||
if (e.getStatusCode() == Response.Status.TOO_MANY_REQUESTS.getStatusCode()) {
|
||||
throw ExceptionUtils.wrap(new RateLimitExceededException(null));
|
||||
}
|
||||
final String details = e instanceof GoogleJsonResponseException
|
||||
? ((GoogleJsonResponseException) e).getDetails().toString()
|
||||
: "";
|
||||
private <R> R executeTokenOperation(final ApiCall<R> apiCall)
|
||||
throws RateLimitExceededException, SubscriptionNotFoundException {
|
||||
try {
|
||||
return apiCall.req(androidPublisher).execute();
|
||||
} catch (HttpResponseException e) {
|
||||
if (e.getStatusCode() == Response.Status.NOT_FOUND.getStatusCode()
|
||||
|| e.getStatusCode() == Response.Status.GONE.getStatusCode()) {
|
||||
throw new SubscriptionNotFoundException();
|
||||
}
|
||||
if (e.getStatusCode() == Response.Status.TOO_MANY_REQUESTS.getStatusCode()) {
|
||||
throw new RateLimitExceededException(null);
|
||||
}
|
||||
final String details = e instanceof GoogleJsonResponseException
|
||||
? ((GoogleJsonResponseException) e).getDetails().toString()
|
||||
: "";
|
||||
|
||||
logger.warn("Unexpected HTTP status code {} from androidpublisher: {}", e.getStatusCode(), details);
|
||||
throw ExceptionUtils.wrap(e);
|
||||
}));
|
||||
logger.warn("Unexpected HTTP status code {} from androidpublisher: {}", e.getStatusCode(), details);
|
||||
throw new UncheckedIOException(e);
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private CompletableFuture<SubscriptionPurchaseV2> lookupSubscription(final String purchaseToken) {
|
||||
private SubscriptionPurchaseV2 lookupSubscription(final String purchaseToken)
|
||||
throws RateLimitExceededException, SubscriptionNotFoundException {
|
||||
return executeTokenOperation(publisher -> publisher.purchases().subscriptionsv2().get(packageName, purchaseToken));
|
||||
}
|
||||
|
||||
|
||||
+309
-334
@@ -5,6 +5,7 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.common.base.Strings;
|
||||
import com.google.common.collect.Lists;
|
||||
import com.stripe.Stripe;
|
||||
@@ -44,6 +45,7 @@ import com.stripe.param.SubscriptionUpdateParams;
|
||||
import com.stripe.param.SubscriptionUpdateParams.BillingCycleAnchor;
|
||||
import com.stripe.param.SubscriptionUpdateParams.ProrationBehavior;
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.InvalidKeyException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
@@ -59,7 +61,6 @@ import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionException;
|
||||
@@ -74,9 +75,9 @@ import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.WhisperServerVersion;
|
||||
import org.whispersystems.textsecuregcm.storage.PaymentTime;
|
||||
import org.whispersystems.textsecuregcm.storage.SubscriptionException;
|
||||
import org.whispersystems.textsecuregcm.util.Conversions;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.util.ExecutorUtil;
|
||||
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
|
||||
|
||||
public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor {
|
||||
@@ -90,19 +91,16 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
private final String boostDescription;
|
||||
private final Map<PaymentMethod, Set<String>> supportedCurrenciesByPaymentMethod;
|
||||
|
||||
public StripeManager(
|
||||
@Nonnull String apiKey,
|
||||
@VisibleForTesting
|
||||
StripeManager(
|
||||
@Nonnull StripeClient stripeClient,
|
||||
@Nonnull Executor executor,
|
||||
@Nonnull byte[] idempotencyKeyGenerator,
|
||||
@Nonnull String boostDescription,
|
||||
@Nonnull Map<PaymentMethod, Set<String>> supportedCurrenciesByPaymentMethod) {
|
||||
if (Strings.isNullOrEmpty(apiKey)) {
|
||||
throw new IllegalArgumentException("apiKey cannot be empty");
|
||||
}
|
||||
|
||||
Stripe.setAppInfo("Signal-Server", WhisperServerVersion.getServerVersion());
|
||||
|
||||
this.stripeClient = new StripeClient(apiKey);
|
||||
this.stripeClient = Objects.requireNonNull(stripeClient);
|
||||
this.executor = Objects.requireNonNull(executor);
|
||||
this.idempotencyKeyGenerator = Objects.requireNonNull(idempotencyKeyGenerator);
|
||||
if (idempotencyKeyGenerator.length == 0) {
|
||||
@@ -111,6 +109,18 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
this.boostDescription = Objects.requireNonNull(boostDescription);
|
||||
this.supportedCurrenciesByPaymentMethod = supportedCurrenciesByPaymentMethod;
|
||||
}
|
||||
public StripeManager(
|
||||
@Nonnull String apiKey,
|
||||
@Nonnull Executor executor,
|
||||
@Nonnull byte[] idempotencyKeyGenerator,
|
||||
@Nonnull String boostDescription,
|
||||
@Nonnull Map<PaymentMethod, Set<String>> supportedCurrenciesByPaymentMethod) {
|
||||
this(new StripeClient(apiKey), executor, idempotencyKeyGenerator, boostDescription, supportedCurrenciesByPaymentMethod);
|
||||
|
||||
if (Strings.isNullOrEmpty(apiKey)) {
|
||||
throw new IllegalArgumentException("apiKey cannot be empty");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public PaymentProvider getProvider() {
|
||||
@@ -135,40 +145,35 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<ProcessorCustomer> createCustomer(final byte[] subscriberUser, @Nullable final ClientPlatform clientPlatform) {
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
final CustomerCreateParams.Builder builder = CustomerCreateParams.builder()
|
||||
.putMetadata("subscriberUser", HexFormat.of().formatHex(subscriberUser));
|
||||
public ProcessorCustomer createCustomer(final byte[] subscriberUser, @Nullable final ClientPlatform clientPlatform) {
|
||||
final CustomerCreateParams.Builder builder = CustomerCreateParams.builder()
|
||||
.putMetadata("subscriberUser", HexFormat.of().formatHex(subscriberUser));
|
||||
|
||||
if (clientPlatform != null) {
|
||||
builder.putMetadata(METADATA_KEY_CLIENT_PLATFORM, clientPlatform.name().toLowerCase());
|
||||
}
|
||||
if (clientPlatform != null) {
|
||||
builder.putMetadata(METADATA_KEY_CLIENT_PLATFORM, clientPlatform.name().toLowerCase());
|
||||
}
|
||||
|
||||
try {
|
||||
return stripeClient.customers()
|
||||
.create(builder.build(), commonOptions(generateIdempotencyKeyForSubscriberUser(subscriberUser)));
|
||||
} catch (StripeException e) {
|
||||
throw new CompletionException(e);
|
||||
}
|
||||
}, executor)
|
||||
.thenApply(customer -> new ProcessorCustomer(customer.getId(), getProvider()));
|
||||
try {
|
||||
final Customer customer = stripeClient.customers()
|
||||
.create(builder.build(), commonOptions(generateIdempotencyKeyForSubscriberUser(subscriberUser)));
|
||||
return new ProcessorCustomer(customer.getId(), getProvider());
|
||||
} catch (StripeException e) {
|
||||
throw new UncheckedIOException(new IOException(e));
|
||||
}
|
||||
}
|
||||
|
||||
public CompletableFuture<Customer> getCustomer(String customerId) {
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
CustomerRetrieveParams params = CustomerRetrieveParams.builder().build();
|
||||
try {
|
||||
return stripeClient.customers().retrieve(customerId, params, commonOptions());
|
||||
} catch (StripeException e) {
|
||||
throw new CompletionException(e);
|
||||
}
|
||||
}, executor);
|
||||
public Customer getCustomer(String customerId) {
|
||||
CustomerRetrieveParams params = CustomerRetrieveParams.builder().build();
|
||||
try {
|
||||
return stripeClient.customers().retrieve(customerId, params, commonOptions());
|
||||
} catch (StripeException e) {
|
||||
throw new UncheckedIOException(new IOException(e));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Void> setDefaultPaymentMethodForCustomer(String customerId, String paymentMethodId,
|
||||
@Nullable String currentSubscriptionId) {
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
public void setDefaultPaymentMethodForCustomer(String customerId, String paymentMethodId,
|
||||
@Nullable String currentSubscriptionId) throws SubscriptionInvalidArgumentsException {
|
||||
CustomerUpdateParams params = CustomerUpdateParams.builder()
|
||||
.setInvoiceSettings(InvoiceSettings.builder()
|
||||
.setDefaultPaymentMethod(paymentMethodId)
|
||||
@@ -176,29 +181,24 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
.build();
|
||||
try {
|
||||
stripeClient.customers().update(customerId, params, commonOptions());
|
||||
return null;
|
||||
} catch (InvalidRequestException e) {
|
||||
// Could happen if the paymentMethodId was bunk or the client didn't actually finish setting it up
|
||||
throw ExceptionUtils.wrap(new SubscriptionException.InvalidArguments(e.getMessage()));
|
||||
throw new SubscriptionInvalidArgumentsException(e.getMessage());
|
||||
} catch (StripeException e) {
|
||||
throw new CompletionException(e);
|
||||
throw new UncheckedIOException(new IOException(e));
|
||||
}
|
||||
}, executor);
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<String> createPaymentMethodSetupToken(String customerId) {
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
SetupIntentCreateParams params = SetupIntentCreateParams.builder()
|
||||
.setCustomer(customerId)
|
||||
.build();
|
||||
try {
|
||||
return stripeClient.setupIntents().create(params, commonOptions());
|
||||
} catch (StripeException e) {
|
||||
throw new CompletionException(e);
|
||||
}
|
||||
}, executor)
|
||||
.thenApply(SetupIntent::getClientSecret);
|
||||
public String createPaymentMethodSetupToken(String customerId) {
|
||||
SetupIntentCreateParams params = SetupIntentCreateParams.builder()
|
||||
.setCustomer(customerId)
|
||||
.build();
|
||||
try {
|
||||
return stripeClient.setupIntents().create(params, commonOptions()).getClientSecret();
|
||||
} catch (StripeException e) {
|
||||
throw new UncheckedIOException(new IOException(e));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -207,7 +207,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a payment intent. May throw a {@link SubscriptionException.InvalidAmount} if stripe rejects the
|
||||
* Creates a payment intent. May throw a {@link SubscriptionInvalidAmountException} if stripe rejects the
|
||||
* attempt if the amount is too large or too small
|
||||
*/
|
||||
public CompletableFuture<PaymentIntent> createPaymentIntent(final String currency,
|
||||
@@ -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) {
|
||||
@@ -232,7 +233,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
final String errorCode = StringUtils.lowerCase(e.getCode(), Locale.ROOT);
|
||||
switch (errorCode) {
|
||||
case "amount_too_small","amount_too_large" ->
|
||||
throw ExceptionUtils.wrap(new SubscriptionException.InvalidAmount(errorCode));
|
||||
throw ExceptionUtils.wrap(new SubscriptionInvalidAmountException(errorCode));
|
||||
default -> throw new CompletionException(e);
|
||||
}
|
||||
}
|
||||
@@ -282,43 +283,44 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<SubscriptionId> createSubscription(String customerId, String priceId, long level,
|
||||
long lastSubscriptionCreatedAt) {
|
||||
public SubscriptionId createSubscription(String customerId, String priceId, long level,
|
||||
long lastSubscriptionCreatedAt)
|
||||
throws SubscriptionProcessorException, SubscriptionInvalidArgumentsException {
|
||||
// this relies on Stripe's idempotency key to avoid creating more than one subscription if the client
|
||||
// retries this request
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
SubscriptionCreateParams params = SubscriptionCreateParams.builder()
|
||||
.setCustomer(customerId)
|
||||
.setOffSession(true)
|
||||
.setPaymentBehavior(SubscriptionCreateParams.PaymentBehavior.ERROR_IF_INCOMPLETE)
|
||||
.addItem(SubscriptionCreateParams.Item.builder()
|
||||
.setPrice(priceId)
|
||||
.build())
|
||||
.putMetadata(METADATA_KEY_LEVEL, Long.toString(level))
|
||||
.build();
|
||||
try {
|
||||
// the idempotency key intentionally excludes priceId
|
||||
//
|
||||
// If the client tells the server several times in a row before the initial creation of a subscription to
|
||||
// create a subscription, we want to ensure only one gets created.
|
||||
return stripeClient.subscriptions()
|
||||
.create(params, commonOptions(generateIdempotencyKeyForCreateSubscription(
|
||||
customerId, lastSubscriptionCreatedAt)));
|
||||
} catch (IdempotencyException e) {
|
||||
throw ExceptionUtils.wrap(new SubscriptionException.InvalidArguments(e.getStripeError().getMessage()));
|
||||
} catch (CardException e) {
|
||||
throw new CompletionException(
|
||||
new SubscriptionException.ProcessorException(getProvider(), createChargeFailureFromCardException(e)));
|
||||
} catch (StripeException e) {
|
||||
throw new CompletionException(e);
|
||||
}
|
||||
}, executor)
|
||||
.thenApply(subscription -> new SubscriptionId(subscription.getId()));
|
||||
SubscriptionCreateParams params = SubscriptionCreateParams.builder()
|
||||
.setCustomer(customerId)
|
||||
.setOffSession(true)
|
||||
.setPaymentBehavior(SubscriptionCreateParams.PaymentBehavior.ERROR_IF_INCOMPLETE)
|
||||
.addItem(SubscriptionCreateParams.Item.builder()
|
||||
.setPrice(priceId)
|
||||
.build())
|
||||
.putMetadata(METADATA_KEY_LEVEL, Long.toString(level))
|
||||
.build();
|
||||
try {
|
||||
// the idempotency key intentionally excludes priceId
|
||||
//
|
||||
// If the client tells the server several times in a row before the initial creation of a subscription to
|
||||
// create a subscription, we want to ensure only one gets created.
|
||||
final Subscription subscription = stripeClient.subscriptions().create(
|
||||
params,
|
||||
commonOptions(generateIdempotencyKeyForCreateSubscription(customerId, lastSubscriptionCreatedAt)));
|
||||
return new SubscriptionId(subscription.getId());
|
||||
} catch (IdempotencyException e) {
|
||||
throw new SubscriptionInvalidArgumentsException(e.getStripeError().getMessage());
|
||||
} catch (CardException e) {
|
||||
throw new SubscriptionProcessorException(getProvider(), createChargeFailureFromCardException(e));
|
||||
} catch (StripeException e) {
|
||||
if ("subscription_payment_intent_requires_action".equals(e.getCode())) {
|
||||
throw new SubscriptionPaymentRequiresActionException();
|
||||
}
|
||||
throw new UncheckedIOException(new IOException(e));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<SubscriptionId> updateSubscription(
|
||||
Object subscriptionObj, String priceId, long level, String idempotencyKey) {
|
||||
public SubscriptionId updateSubscription(Object subscriptionObj, String priceId, long level, String idempotencyKey)
|
||||
throws SubscriptionInvalidArgumentsException, SubscriptionProcessorException {
|
||||
|
||||
final Subscription subscription = getSubscription(subscriptionObj);
|
||||
|
||||
@@ -328,101 +330,92 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
return createSubscription(subscription.getCustomer(), priceId, level, subscription.getCreated());
|
||||
}
|
||||
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
List<SubscriptionUpdateParams.Item> items = new ArrayList<>();
|
||||
try {
|
||||
final StripeCollection<SubscriptionItem> subscriptionItems = stripeClient.subscriptionItems()
|
||||
.list(SubscriptionItemListParams.builder().setSubscription(subscription.getId()).build(),
|
||||
commonOptions());
|
||||
for (final SubscriptionItem item : subscriptionItems.autoPagingIterable()) {
|
||||
items.add(SubscriptionUpdateParams.Item.builder()
|
||||
.setId(item.getId())
|
||||
.setDeleted(true)
|
||||
.build());
|
||||
}
|
||||
items.add(SubscriptionUpdateParams.Item.builder()
|
||||
.setPrice(priceId)
|
||||
.build());
|
||||
SubscriptionUpdateParams params = SubscriptionUpdateParams.builder()
|
||||
.putMetadata(METADATA_KEY_LEVEL, Long.toString(level))
|
||||
|
||||
// since badge redemption is untrackable by design and unrevokable, subscription changes must be immediate and
|
||||
// not prorated
|
||||
.setProrationBehavior(ProrationBehavior.NONE)
|
||||
.setBillingCycleAnchor(BillingCycleAnchor.NOW)
|
||||
.setOffSession(true)
|
||||
.setPaymentBehavior(SubscriptionUpdateParams.PaymentBehavior.ERROR_IF_INCOMPLETE)
|
||||
.addAllItem(items)
|
||||
.build();
|
||||
return stripeClient.subscriptions().update(subscription.getId(), params,
|
||||
commonOptions(
|
||||
generateIdempotencyKeyForSubscriptionUpdate(subscription.getCustomer(), idempotencyKey)));
|
||||
} catch (IdempotencyException e) {
|
||||
throw ExceptionUtils.wrap(new SubscriptionException.InvalidArguments(e.getStripeError().getMessage()));
|
||||
} catch (CardException e) {
|
||||
throw ExceptionUtils.wrap(
|
||||
new SubscriptionException.ProcessorException(getProvider(), createChargeFailureFromCardException(e)));
|
||||
} catch (StripeException e) {
|
||||
throw ExceptionUtils.wrap(e);
|
||||
}
|
||||
}, executor)
|
||||
.thenApply(subscription1 -> new SubscriptionId(subscription1.getId()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Object> getSubscription(String subscriptionId) {
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
SubscriptionRetrieveParams params = SubscriptionRetrieveParams.builder()
|
||||
.addExpand("latest_invoice")
|
||||
.addExpand("latest_invoice.charge")
|
||||
.build();
|
||||
try {
|
||||
return stripeClient.subscriptions().retrieve(subscriptionId, params, commonOptions());
|
||||
} catch (StripeException e) {
|
||||
throw new CompletionException(e);
|
||||
List<SubscriptionUpdateParams.Item> items = new ArrayList<>();
|
||||
try {
|
||||
final StripeCollection<SubscriptionItem> subscriptionItems = stripeClient.subscriptionItems()
|
||||
.list(SubscriptionItemListParams.builder().setSubscription(subscription.getId()).build(),
|
||||
commonOptions());
|
||||
for (final SubscriptionItem item : subscriptionItems.autoPagingIterable()) {
|
||||
items.add(SubscriptionUpdateParams.Item.builder()
|
||||
.setId(item.getId())
|
||||
.setDeleted(true)
|
||||
.build());
|
||||
}
|
||||
}, executor);
|
||||
items.add(SubscriptionUpdateParams.Item.builder()
|
||||
.setPrice(priceId)
|
||||
.build());
|
||||
SubscriptionUpdateParams params = SubscriptionUpdateParams.builder()
|
||||
.putMetadata(METADATA_KEY_LEVEL, Long.toString(level))
|
||||
|
||||
// since badge redemption is untrackable by design and unrevokable, subscription changes must be immediate and
|
||||
// not prorated
|
||||
.setProrationBehavior(ProrationBehavior.NONE)
|
||||
.setBillingCycleAnchor(BillingCycleAnchor.NOW)
|
||||
.setOffSession(true)
|
||||
.setPaymentBehavior(SubscriptionUpdateParams.PaymentBehavior.ERROR_IF_INCOMPLETE)
|
||||
.addAllItem(items)
|
||||
.build();
|
||||
final Subscription subscription1 = stripeClient.subscriptions().update(subscription.getId(), params,
|
||||
commonOptions(generateIdempotencyKeyForSubscriptionUpdate(subscription.getCustomer(), idempotencyKey)));
|
||||
return new SubscriptionId(subscription1.getId());
|
||||
} catch (IdempotencyException e) {
|
||||
throw new SubscriptionInvalidArgumentsException(e.getStripeError().getMessage());
|
||||
} catch (CardException e) {
|
||||
throw new SubscriptionProcessorException(getProvider(), createChargeFailureFromCardException(e));
|
||||
} catch (StripeException e) {
|
||||
throw new UncheckedIOException(new IOException(e));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Void> cancelAllActiveSubscriptions(String customerId) {
|
||||
return getCustomer(customerId).thenCompose(customer -> {
|
||||
public Object getSubscription(String subscriptionId) {
|
||||
SubscriptionRetrieveParams params = SubscriptionRetrieveParams.builder()
|
||||
.addExpand("latest_invoice")
|
||||
.addExpand("latest_invoice.charge")
|
||||
.build();
|
||||
try {
|
||||
return stripeClient.subscriptions().retrieve(subscriptionId, params, commonOptions());
|
||||
} catch (StripeException e) {
|
||||
throw new UncheckedIOException(new IOException(e));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void cancelAllActiveSubscriptions(String customerId) {
|
||||
final Customer customer = getCustomer(customerId);
|
||||
if (customer == null) {
|
||||
throw ExceptionUtils.wrap(new IOException("no customer record found for id " + customerId));
|
||||
throw new UncheckedIOException(new IOException("no customer record found for id " + customerId));
|
||||
}
|
||||
if (StringUtils.isBlank(customer.getId()) || (!customer.getId().equals(customerId))) {
|
||||
logger.error("customer ID returned by Stripe ({}) did not match query ({})", customerId, customer.getSubscriptions());
|
||||
throw ExceptionUtils.wrap(new IOException("unexpected customer ID returned by Stripe"));
|
||||
throw new UncheckedIOException(new IOException("unexpected customer ID returned by Stripe"));
|
||||
}
|
||||
return listNonCanceledSubscriptions(customer);
|
||||
}).thenCompose(subscriptions -> {
|
||||
if (subscriptions.stream()
|
||||
.anyMatch(subscription -> !subscription.getCustomer().equals(customerId))) {
|
||||
logger.error("Subscription did not match expected customer ID: {}", customerId);
|
||||
throw ExceptionUtils.wrap( new IOException("mismatched customer ID"));
|
||||
}
|
||||
@SuppressWarnings("unchecked")
|
||||
CompletableFuture<Subscription>[] futures = (CompletableFuture<Subscription>[]) subscriptions.stream()
|
||||
.map(this::endSubscription).toArray(CompletableFuture[]::new);
|
||||
return CompletableFuture.allOf(futures);
|
||||
});
|
||||
|
||||
final Collection<Subscription> subscriptions = listNonCanceledSubscriptions(customer);
|
||||
if (subscriptions.stream()
|
||||
.anyMatch(subscription -> !subscription.getCustomer().equals(customerId))) {
|
||||
logger.error("Subscription did not match expected customer ID: {}", customerId);
|
||||
throw new UncheckedIOException(new IOException("mismatched customer ID"));
|
||||
}
|
||||
ExecutorUtil.runAll(executor, subscriptions
|
||||
.stream()
|
||||
.<Runnable>map(subscription -> () -> this.endSubscription(subscription))
|
||||
.toList());
|
||||
}
|
||||
|
||||
public CompletableFuture<Collection<Subscription>> listNonCanceledSubscriptions(Customer customer) {
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
SubscriptionListParams params = SubscriptionListParams.builder()
|
||||
.setCustomer(customer.getId())
|
||||
.build();
|
||||
try {
|
||||
return Lists.newArrayList(
|
||||
stripeClient.subscriptions().list(params, commonOptions()).autoPagingIterable());
|
||||
} catch (StripeException e) {
|
||||
throw new CompletionException(e);
|
||||
}
|
||||
}, executor);
|
||||
public Collection<Subscription> listNonCanceledSubscriptions(Customer customer) {
|
||||
SubscriptionListParams params = SubscriptionListParams.builder()
|
||||
.setCustomer(customer.getId())
|
||||
.build();
|
||||
try {
|
||||
return Lists.newArrayList(
|
||||
stripeClient.subscriptions().list(params, commonOptions()).autoPagingIterable());
|
||||
} catch (StripeException e) {
|
||||
throw new UncheckedIOException(new IOException(e));
|
||||
}
|
||||
}
|
||||
|
||||
private CompletableFuture<Subscription> endSubscription(Subscription subscription) {
|
||||
private Subscription endSubscription(Subscription subscription) {
|
||||
final SubscriptionStatus status = SubscriptionStatus.forApiValue(subscription.getStatus());
|
||||
return switch (status) {
|
||||
// The payment for this period has not processed yet, we should immediately cancel to prevent any payment from
|
||||
@@ -434,84 +427,74 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
};
|
||||
}
|
||||
|
||||
private CompletableFuture<Subscription> cancelSubscriptionImmediately(Subscription subscription) {
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
SubscriptionCancelParams params = SubscriptionCancelParams.builder().build();
|
||||
try {
|
||||
return stripeClient.subscriptions().cancel(subscription.getId(), params, commonOptions());
|
||||
} catch (StripeException e) {
|
||||
throw new CompletionException(e);
|
||||
}
|
||||
}, executor);
|
||||
private Subscription cancelSubscriptionImmediately(Subscription subscription) {
|
||||
SubscriptionCancelParams params = SubscriptionCancelParams.builder().build();
|
||||
try {
|
||||
return stripeClient.subscriptions().cancel(subscription.getId(), params, commonOptions());
|
||||
} catch (StripeException e) {
|
||||
throw new UncheckedIOException(new IOException(e));
|
||||
}
|
||||
}
|
||||
|
||||
private CompletableFuture<Subscription> cancelSubscriptionAtEndOfCurrentPeriod(Subscription subscription) {
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
SubscriptionUpdateParams params = SubscriptionUpdateParams.builder()
|
||||
.setCancelAtPeriodEnd(true)
|
||||
.build();
|
||||
try {
|
||||
return stripeClient.subscriptions().update(subscription.getId(), params, commonOptions());
|
||||
} catch (StripeException e) {
|
||||
throw new CompletionException(e);
|
||||
}
|
||||
}, executor);
|
||||
private Subscription cancelSubscriptionAtEndOfCurrentPeriod(Subscription subscription) {
|
||||
SubscriptionUpdateParams params = SubscriptionUpdateParams.builder()
|
||||
.setCancelAtPeriodEnd(true)
|
||||
.build();
|
||||
try {
|
||||
return stripeClient.subscriptions().update(subscription.getId(), params, commonOptions());
|
||||
} catch (StripeException e) {
|
||||
throw new UncheckedIOException(new IOException(e));
|
||||
}
|
||||
}
|
||||
|
||||
public CompletableFuture<Collection<SubscriptionItem>> getItemsForSubscription(Subscription subscription) {
|
||||
return CompletableFuture.supplyAsync(
|
||||
() -> {
|
||||
try {
|
||||
final StripeCollection<SubscriptionItem> subscriptionItems = stripeClient.subscriptionItems().list(
|
||||
SubscriptionItemListParams.builder().setSubscription(subscription.getId()).build(), commonOptions());
|
||||
return Lists.newArrayList(subscriptionItems.autoPagingIterable());
|
||||
public Collection<SubscriptionItem> getItemsForSubscription(Subscription subscription) {
|
||||
try {
|
||||
final StripeCollection<SubscriptionItem> subscriptionItems = stripeClient.subscriptionItems().list(
|
||||
SubscriptionItemListParams.builder().setSubscription(subscription.getId()).build(), commonOptions());
|
||||
return Lists.newArrayList(subscriptionItems.autoPagingIterable());
|
||||
|
||||
} catch (final StripeException e) {
|
||||
throw new CompletionException(e);
|
||||
}
|
||||
},
|
||||
executor);
|
||||
} catch (final StripeException e) {
|
||||
throw new UncheckedIOException(new IOException(e));
|
||||
}
|
||||
}
|
||||
|
||||
public CompletableFuture<Price> getPriceForSubscription(Subscription subscription) {
|
||||
return getItemsForSubscription(subscription).thenApply(subscriptionItems -> {
|
||||
if (subscriptionItems.isEmpty()) {
|
||||
throw new IllegalStateException("no items found in subscription " + subscription.getId());
|
||||
} else if (subscriptionItems.size() > 1) {
|
||||
throw new IllegalStateException(
|
||||
"too many items found in subscription " + subscription.getId() + "; items=" + subscriptionItems.size());
|
||||
} else {
|
||||
return subscriptionItems.stream().findAny().get().getPrice();
|
||||
}
|
||||
});
|
||||
public Price getPriceForSubscription(Subscription subscription) {
|
||||
final Collection<SubscriptionItem> subscriptionItems = getItemsForSubscription(subscription);
|
||||
if (subscriptionItems.isEmpty()) {
|
||||
throw new IllegalStateException("no items found in subscription " + subscription.getId());
|
||||
} else if (subscriptionItems.size() > 1) {
|
||||
throw new IllegalStateException(
|
||||
"too many items found in subscription " + subscription.getId() + "; items=" + subscriptionItems.size());
|
||||
} else {
|
||||
return subscriptionItems.stream().findAny().get().getPrice();
|
||||
}
|
||||
}
|
||||
|
||||
private CompletableFuture<Product> getProductForSubscription(Subscription subscription) {
|
||||
return getPriceForSubscription(subscription).thenCompose(price -> getProductForPrice(price.getId()));
|
||||
private Product getProductForSubscription(Subscription subscription) {
|
||||
return getProductForPrice(getPriceForSubscription(subscription).getId());
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<LevelAndCurrency> getLevelAndCurrencyForSubscription(Object subscriptionObj) {
|
||||
public LevelAndCurrency getLevelAndCurrencyForSubscription(Object subscriptionObj) {
|
||||
final Subscription subscription = getSubscription(subscriptionObj);
|
||||
|
||||
return getProductForSubscription(subscription).thenApply(
|
||||
product -> new LevelAndCurrency(getLevelForProduct(product), subscription.getCurrency().toLowerCase(
|
||||
Locale.ROOT)));
|
||||
final Product product = getProductForSubscription(subscription);
|
||||
return new LevelAndCurrency(
|
||||
getLevelForProduct(product),
|
||||
subscription.getCurrency().toLowerCase(Locale.ROOT));
|
||||
}
|
||||
|
||||
public CompletableFuture<Long> getLevelForPrice(Price price) {
|
||||
return getProductForPrice(price.getId()).thenApply(this::getLevelForProduct);
|
||||
public long getLevelForPrice(Price price) {
|
||||
return getLevelForProduct(getProductForPrice(price.getId()));
|
||||
}
|
||||
|
||||
public CompletableFuture<Product> getProductForPrice(String priceId) {
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
PriceRetrieveParams params = PriceRetrieveParams.builder().addExpand("product").build();
|
||||
try {
|
||||
return stripeClient.prices().retrieve(priceId, params, commonOptions()).getProductObject();
|
||||
} catch (StripeException e) {
|
||||
throw new CompletionException(e);
|
||||
}
|
||||
}, executor);
|
||||
public Product getProductForPrice(String priceId) {
|
||||
PriceRetrieveParams params = PriceRetrieveParams.builder().addExpand("product").build();
|
||||
try {
|
||||
return stripeClient.prices().retrieve(priceId, params, commonOptions()).getProductObject();
|
||||
} catch (StripeException e) {
|
||||
throw new UncheckedIOException(new IOException(e));
|
||||
}
|
||||
}
|
||||
|
||||
public long getLevelForProduct(Product product) {
|
||||
@@ -522,24 +505,22 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
* Returns the paid invoices within the past 90 days for a subscription ordered by the creation date in descending
|
||||
* order (latest first).
|
||||
*/
|
||||
public CompletableFuture<Collection<Invoice>> getPaidInvoicesForSubscription(String subscriptionId, Instant now) {
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
InvoiceListParams params = InvoiceListParams.builder()
|
||||
.setSubscription(subscriptionId)
|
||||
.setStatus(InvoiceListParams.Status.PAID)
|
||||
.setCreated(InvoiceListParams.Created.builder()
|
||||
.setGte(now.minus(Duration.ofDays(90)).getEpochSecond())
|
||||
.build())
|
||||
.build();
|
||||
try {
|
||||
ArrayList<Invoice> invoices = Lists.newArrayList(stripeClient.invoices().list(params, commonOptions())
|
||||
.autoPagingIterable());
|
||||
invoices.sort(Comparator.comparingLong(Invoice::getCreated).reversed());
|
||||
return invoices;
|
||||
} catch (StripeException e) {
|
||||
throw new CompletionException(e);
|
||||
}
|
||||
}, executor);
|
||||
public Collection<Invoice> getPaidInvoicesForSubscription(String subscriptionId, Instant now) {
|
||||
InvoiceListParams params = InvoiceListParams.builder()
|
||||
.setSubscription(subscriptionId)
|
||||
.setStatus(InvoiceListParams.Status.PAID)
|
||||
.setCreated(InvoiceListParams.Created.builder()
|
||||
.setGte(now.minus(Duration.ofDays(90)).getEpochSecond())
|
||||
.build())
|
||||
.build();
|
||||
try {
|
||||
ArrayList<Invoice> invoices = Lists.newArrayList(stripeClient.invoices().list(params, commonOptions())
|
||||
.autoPagingIterable());
|
||||
invoices.sort(Comparator.comparingLong(Invoice::getCreated).reversed());
|
||||
return invoices;
|
||||
} catch (StripeException e) {
|
||||
throw new UncheckedIOException(new IOException(e));
|
||||
}
|
||||
}
|
||||
|
||||
private static ChargeFailure createChargeFailure(final Charge charge) {
|
||||
@@ -563,45 +544,45 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<SubscriptionInformation> getSubscriptionInformation(final String subscriptionId) {
|
||||
return getSubscription(subscriptionId).thenApply(this::getSubscription).thenCompose(subscription ->
|
||||
getPriceForSubscription(subscription).thenCompose(price ->
|
||||
getLevelForPrice(price).thenApply(level -> {
|
||||
ChargeFailure chargeFailure = null;
|
||||
boolean paymentProcessing = false;
|
||||
PaymentMethod paymentMethod = null;
|
||||
public SubscriptionInformation getSubscriptionInformation(final String subscriptionId) {
|
||||
final Subscription subscription = getSubscription(getSubscription(subscriptionId));
|
||||
final Price price = getPriceForSubscription(subscription);
|
||||
final long level = getLevelForPrice(price);
|
||||
|
||||
if (subscription.getLatestInvoiceObject() != null) {
|
||||
final Invoice invoice = subscription.getLatestInvoiceObject();
|
||||
paymentProcessing = "open".equals(invoice.getStatus());
|
||||
ChargeFailure chargeFailure = null;
|
||||
boolean paymentProcessing = false;
|
||||
PaymentMethod paymentMethod = null;
|
||||
|
||||
if (invoice.getChargeObject() != null) {
|
||||
final Charge charge = invoice.getChargeObject();
|
||||
if (charge.getFailureCode() != null || charge.getFailureMessage() != null) {
|
||||
chargeFailure = createChargeFailure(charge);
|
||||
}
|
||||
if (subscription.getLatestInvoiceObject() != null) {
|
||||
final Invoice invoice = subscription.getLatestInvoiceObject();
|
||||
paymentProcessing = "open".equals(invoice.getStatus());
|
||||
|
||||
if (charge.getPaymentMethodDetails() != null
|
||||
&& charge.getPaymentMethodDetails().getType() != null) {
|
||||
paymentMethod = getPaymentMethodFromStripeString(charge.getPaymentMethodDetails().getType(), invoice.getId());
|
||||
}
|
||||
}
|
||||
}
|
||||
if (invoice.getChargeObject() != null) {
|
||||
final Charge charge = invoice.getChargeObject();
|
||||
if (charge.getFailureCode() != null || charge.getFailureMessage() != null) {
|
||||
chargeFailure = createChargeFailure(charge);
|
||||
}
|
||||
|
||||
return new SubscriptionInformation(
|
||||
new SubscriptionPrice(price.getCurrency().toUpperCase(Locale.ROOT), price.getUnitAmountDecimal()),
|
||||
level,
|
||||
Instant.ofEpochSecond(subscription.getBillingCycleAnchor()),
|
||||
Instant.ofEpochSecond(subscription.getCurrentPeriodEnd()),
|
||||
Objects.equals(subscription.getStatus(), "active"),
|
||||
subscription.getCancelAtPeriodEnd(),
|
||||
getSubscriptionStatus(subscription.getStatus()),
|
||||
PaymentProvider.STRIPE,
|
||||
paymentMethod,
|
||||
paymentProcessing,
|
||||
chargeFailure
|
||||
);
|
||||
})));
|
||||
if (charge.getPaymentMethodDetails() != null
|
||||
&& charge.getPaymentMethodDetails().getType() != null) {
|
||||
paymentMethod = getPaymentMethodFromStripeString(charge.getPaymentMethodDetails().getType(), invoice.getId());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return new SubscriptionInformation(
|
||||
new SubscriptionPrice(price.getCurrency().toUpperCase(Locale.ROOT), price.getUnitAmountDecimal()),
|
||||
level,
|
||||
Instant.ofEpochSecond(subscription.getBillingCycleAnchor()),
|
||||
Instant.ofEpochSecond(subscription.getCurrentPeriodEnd()),
|
||||
Objects.equals(subscription.getStatus(), "active"),
|
||||
subscription.getCancelAtPeriodEnd(),
|
||||
getSubscriptionStatus(subscription.getStatus()),
|
||||
PaymentProvider.STRIPE,
|
||||
paymentMethod,
|
||||
paymentProcessing,
|
||||
chargeFailure
|
||||
);
|
||||
}
|
||||
|
||||
private static PaymentMethod getPaymentMethodFromStripeString(final String paymentMethodString, final String invoiceId) {
|
||||
@@ -624,79 +605,73 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<ReceiptItem> getReceiptItem(String subscriptionId) {
|
||||
return getSubscription(subscriptionId)
|
||||
.thenApply(stripeSubscription -> getSubscription(stripeSubscription).getLatestInvoiceObject())
|
||||
.thenCompose(invoice -> convertInvoiceToReceipt(invoice, subscriptionId));
|
||||
public ReceiptItem getReceiptItem(String subscriptionId)
|
||||
throws SubscriptionPaymentRequiredException, SubscriptionReceiptRequestedForOpenPaymentException {
|
||||
final Invoice invoice = getSubscription(getSubscription(subscriptionId)).getLatestInvoiceObject();
|
||||
return convertInvoiceToReceipt(invoice, subscriptionId);
|
||||
}
|
||||
|
||||
private CompletableFuture<ReceiptItem> convertInvoiceToReceipt(Invoice latestSubscriptionInvoice, String subscriptionId) {
|
||||
private ReceiptItem convertInvoiceToReceipt(Invoice latestSubscriptionInvoice, String subscriptionId)
|
||||
throws SubscriptionReceiptRequestedForOpenPaymentException, SubscriptionPaymentRequiredException {
|
||||
if (latestSubscriptionInvoice == null) {
|
||||
return CompletableFuture.failedFuture(
|
||||
ExceptionUtils.wrap(new SubscriptionException.ReceiptRequestedForOpenPayment()));
|
||||
throw new SubscriptionReceiptRequestedForOpenPaymentException();
|
||||
}
|
||||
if (StringUtils.equalsIgnoreCase("open", latestSubscriptionInvoice.getStatus())) {
|
||||
return CompletableFuture.failedFuture(
|
||||
ExceptionUtils.wrap(new SubscriptionException.ReceiptRequestedForOpenPayment()));
|
||||
throw new SubscriptionReceiptRequestedForOpenPaymentException();
|
||||
}
|
||||
if (!StringUtils.equalsIgnoreCase("paid", latestSubscriptionInvoice.getStatus())) {
|
||||
return CompletableFuture.failedFuture(ExceptionUtils.wrap(Optional
|
||||
.ofNullable(latestSubscriptionInvoice.getChargeObject())
|
||||
|
||||
// If the charge object has a failure reason we can present to the user, create a detailed exception
|
||||
.filter(charge -> charge.getFailureCode() != null || charge.getFailureMessage() != null)
|
||||
.<SubscriptionException> map(charge ->
|
||||
new SubscriptionException.ChargeFailurePaymentRequired(getProvider(), createChargeFailure(charge)))
|
||||
|
||||
// Otherwise, return a generic payment required error
|
||||
.orElseGet(() -> new SubscriptionException.PaymentRequired())));
|
||||
final Charge charge = latestSubscriptionInvoice.getChargeObject();
|
||||
if (charge != null && (charge.getFailureCode() != null || charge.getFailureMessage() != null)) {
|
||||
// If the charge object has a failure reason we can present to the user, create a detailed exception
|
||||
throw new SubscriptionChargeFailurePaymentRequiredException(getProvider(), createChargeFailure(charge));
|
||||
} else {
|
||||
// Otherwise, return a generic payment required error
|
||||
throw new SubscriptionPaymentRequiredException();
|
||||
}
|
||||
}
|
||||
|
||||
return getInvoiceLineItemsForInvoice(latestSubscriptionInvoice).thenCompose(invoiceLineItems -> {
|
||||
Collection<InvoiceLineItem> subscriptionLineItems = invoiceLineItems.stream()
|
||||
.filter(invoiceLineItem -> Objects.equals("subscription", invoiceLineItem.getType()))
|
||||
.toList();
|
||||
if (subscriptionLineItems.isEmpty()) {
|
||||
throw new IllegalStateException("latest subscription invoice has no subscription line items; subscriptionId="
|
||||
+ subscriptionId + "; invoiceId=" + latestSubscriptionInvoice.getId());
|
||||
}
|
||||
if (subscriptionLineItems.size() > 1) {
|
||||
throw new IllegalStateException(
|
||||
"latest subscription invoice has too many subscription line items; subscriptionId=" + subscriptionId
|
||||
+ "; invoiceId=" + latestSubscriptionInvoice.getId() + "; count=" + subscriptionLineItems.size());
|
||||
}
|
||||
final Collection<InvoiceLineItem> invoiceLineItems = getInvoiceLineItemsForInvoice(latestSubscriptionInvoice);
|
||||
Collection<InvoiceLineItem> subscriptionLineItems = invoiceLineItems.stream()
|
||||
.filter(invoiceLineItem -> Objects.equals("subscription", invoiceLineItem.getType()))
|
||||
.toList();
|
||||
if (subscriptionLineItems.isEmpty()) {
|
||||
throw new IllegalStateException("latest subscription invoice has no subscription line items; subscriptionId="
|
||||
+ subscriptionId + "; invoiceId=" + latestSubscriptionInvoice.getId());
|
||||
}
|
||||
if (subscriptionLineItems.size() > 1) {
|
||||
throw new IllegalStateException(
|
||||
"latest subscription invoice has too many subscription line items; subscriptionId=" + subscriptionId
|
||||
+ "; invoiceId=" + latestSubscriptionInvoice.getId() + "; count=" + subscriptionLineItems.size());
|
||||
}
|
||||
|
||||
InvoiceLineItem subscriptionLineItem = subscriptionLineItems.stream().findAny().get();
|
||||
return getReceiptForSubscription(subscriptionLineItem, latestSubscriptionInvoice);
|
||||
});
|
||||
InvoiceLineItem subscriptionLineItem = subscriptionLineItems.stream().findAny().get();
|
||||
return getReceiptForSubscription(subscriptionLineItem, latestSubscriptionInvoice);
|
||||
}
|
||||
|
||||
private CompletableFuture<ReceiptItem> getReceiptForSubscription(InvoiceLineItem subscriptionLineItem,
|
||||
Invoice invoice) {
|
||||
private ReceiptItem getReceiptForSubscription(InvoiceLineItem subscriptionLineItem, Invoice invoice) {
|
||||
final Instant paidAt;
|
||||
if (invoice.getStatusTransitions().getPaidAt() != null) {
|
||||
paidAt = Instant.ofEpochSecond(invoice.getStatusTransitions().getPaidAt());
|
||||
} else {
|
||||
logger.warn("No paidAt timestamp exists for paid invoice {}, falling back to start of subscription period", invoice.getId());
|
||||
logger.warn("No paidAt timestamp exists for paid invoice {}, falling back to start of subscription period",
|
||||
invoice.getId());
|
||||
paidAt = Instant.ofEpochSecond(subscriptionLineItem.getPeriod().getStart());
|
||||
}
|
||||
return getProductForPrice(subscriptionLineItem.getPrice().getId()).thenApply(product -> new ReceiptItem(
|
||||
final Product product = getProductForPrice(subscriptionLineItem.getPrice().getId());
|
||||
return new ReceiptItem(
|
||||
subscriptionLineItem.getId(),
|
||||
PaymentTime.periodStart(paidAt),
|
||||
getLevelForProduct(product)));
|
||||
getLevelForProduct(product));
|
||||
}
|
||||
|
||||
public CompletableFuture<Collection<InvoiceLineItem>> getInvoiceLineItemsForInvoice(Invoice invoice) {
|
||||
return CompletableFuture.supplyAsync(
|
||||
() -> {
|
||||
try {
|
||||
final StripeCollection<InvoiceLineItem> lineItems = stripeClient.invoices().lineItems()
|
||||
.list(invoice.getId(), commonOptions());
|
||||
return Lists.newArrayList(lineItems.autoPagingIterable());
|
||||
} catch (final StripeException e) {
|
||||
throw new CompletionException(e);
|
||||
}
|
||||
}, executor);
|
||||
public Collection<InvoiceLineItem> getInvoiceLineItemsForInvoice(Invoice invoice) {
|
||||
try {
|
||||
final StripeCollection<InvoiceLineItem> lineItems = stripeClient.invoices().lineItems()
|
||||
.list(invoice.getId(), commonOptions());
|
||||
return Lists.newArrayList(lineItems.autoPagingIterable());
|
||||
} catch (final StripeException e) {
|
||||
throw new UncheckedIOException(new IOException(e));
|
||||
}
|
||||
}
|
||||
|
||||
public CompletableFuture<String> getGeneratedSepaIdFromSetupIntent(String setupIntentId) {
|
||||
@@ -713,12 +688,12 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
// This usually indicates that the client has made requests out of order, either by not confirming
|
||||
// the SetupIntent or not having the user authorize the transaction.
|
||||
logger.debug("setupIntent {} missing expected fields", setupIntentId);
|
||||
throw ExceptionUtils.wrap(new SubscriptionException.ProcessorConflict());
|
||||
throw ExceptionUtils.wrap(new SubscriptionProcessorConflictException());
|
||||
}
|
||||
return setupIntent.getLatestAttemptObject().getPaymentMethodDetails().getIdeal().getGeneratedSepaDebit();
|
||||
} catch (StripeException e) {
|
||||
if (e.getStatusCode() == 404) {
|
||||
throw ExceptionUtils.wrap(new SubscriptionException.NotFound());
|
||||
throw ExceptionUtils.wrap(new SubscriptionNotFoundException());
|
||||
}
|
||||
logger.error("unexpected error from Stripe when retrieving setupIntent {}", setupIntentId, e);
|
||||
throw ExceptionUtils.wrap(e);
|
||||
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
|
||||
public class SubscriptionChargeFailurePaymentRequiredException extends SubscriptionPaymentRequiredException {
|
||||
|
||||
private final PaymentProvider processor;
|
||||
private final ChargeFailure chargeFailure;
|
||||
|
||||
public SubscriptionChargeFailurePaymentRequiredException(final PaymentProvider processor,
|
||||
final ChargeFailure chargeFailure) {
|
||||
super();
|
||||
this.processor = processor;
|
||||
this.chargeFailure = chargeFailure;
|
||||
}
|
||||
|
||||
public PaymentProvider getProcessor() {
|
||||
return processor;
|
||||
}
|
||||
|
||||
public ChargeFailure getChargeFailure() {
|
||||
return chargeFailure;
|
||||
}
|
||||
|
||||
}
|
||||
+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);
|
||||
}
|
||||
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
|
||||
import java.util.Optional;
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
public class SubscriptionException extends Exception {
|
||||
|
||||
private @Nullable String errorDetail;
|
||||
|
||||
public SubscriptionException(Exception cause) {
|
||||
this(cause, null);
|
||||
}
|
||||
|
||||
SubscriptionException(Exception cause, String errorDetail) {
|
||||
super(cause);
|
||||
this.errorDetail = errorDetail;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return An error message suitable to include in a client response
|
||||
*/
|
||||
public Optional<String> errorDetail() {
|
||||
return Optional.ofNullable(errorDetail);
|
||||
}
|
||||
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
|
||||
public class SubscriptionForbiddenException extends SubscriptionException {
|
||||
|
||||
public SubscriptionForbiddenException(final String message) {
|
||||
super(null, message);
|
||||
}
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
|
||||
public class SubscriptionInvalidAmountException extends SubscriptionInvalidArgumentsException {
|
||||
|
||||
private String errorCode;
|
||||
|
||||
public SubscriptionInvalidAmountException(String errorCode) {
|
||||
super(null, null);
|
||||
this.errorCode = errorCode;
|
||||
}
|
||||
|
||||
public String getErrorCode() {
|
||||
return errorCode;
|
||||
}
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
|
||||
public class SubscriptionInvalidArgumentsException extends SubscriptionException {
|
||||
|
||||
public SubscriptionInvalidArgumentsException(final String message, final Exception cause) {
|
||||
super(cause, message);
|
||||
}
|
||||
|
||||
public SubscriptionInvalidArgumentsException(final String message) {
|
||||
this(message, null);
|
||||
}
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
|
||||
public class SubscriptionInvalidLevelException extends SubscriptionInvalidArgumentsException {
|
||||
|
||||
public SubscriptionInvalidLevelException() {
|
||||
super(null, null);
|
||||
}
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
|
||||
public class SubscriptionNotFoundException extends SubscriptionException {
|
||||
|
||||
public SubscriptionNotFoundException() {
|
||||
super(null);
|
||||
}
|
||||
|
||||
public SubscriptionNotFoundException(Exception cause) {
|
||||
super(cause);
|
||||
}
|
||||
}
|
||||
+25
-7
@@ -4,10 +4,9 @@
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.storage.PaymentTime;
|
||||
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
public interface SubscriptionPaymentProcessor {
|
||||
|
||||
PaymentProvider getProvider();
|
||||
@@ -27,17 +26,36 @@ public interface SubscriptionPaymentProcessor {
|
||||
*
|
||||
* @param subscriptionId A subscriptionId that potentially corresponds to a valid subscription
|
||||
* @return A {@link ReceiptItem} if the subscription is valid
|
||||
* @throws RateLimitExceededException If rate-limited
|
||||
* @throws SubscriptionNotFoundException If the provided subscriptionId could not be found with
|
||||
* the provider
|
||||
* @throws SubscriptionPaymentRequiredException If the subscription is in a state does not grant the
|
||||
* user an entitlement
|
||||
* @throws SubscriptionReceiptRequestedForOpenPaymentException If a receipt was requested while a payment transaction
|
||||
* was still open
|
||||
*/
|
||||
CompletableFuture<ReceiptItem> getReceiptItem(String subscriptionId);
|
||||
ReceiptItem getReceiptItem(String subscriptionId)
|
||||
throws RateLimitExceededException, SubscriptionNotFoundException, SubscriptionChargeFailurePaymentRequiredException, SubscriptionPaymentRequiredException, SubscriptionReceiptRequestedForOpenPaymentException;
|
||||
|
||||
/**
|
||||
* Cancel all active subscriptions for this key within the payment provider.
|
||||
* Cancel all active subscriptions for this key within the payment processor.
|
||||
*
|
||||
* @param key An identifier for the subscriber within the payment provider, corresponds to the customerId field in the
|
||||
* subscriptions table
|
||||
* @return A stage that completes when all subscriptions associated with the key are cancelled
|
||||
* @throws RateLimitExceededException If rate-limited
|
||||
* @throws SubscriptionInvalidArgumentsException If a precondition for cancellation was not met
|
||||
*/
|
||||
CompletableFuture<Void> cancelAllActiveSubscriptions(String key);
|
||||
void cancelAllActiveSubscriptions(String key)
|
||||
throws SubscriptionInvalidArgumentsException, RateLimitExceededException;
|
||||
|
||||
CompletableFuture<SubscriptionInformation> getSubscriptionInformation(final String subscriptionId);
|
||||
/**
|
||||
* Retrieve subscription information from the processor
|
||||
*
|
||||
* @param subscriptionId The identifier with the processor to retrieve information for
|
||||
* @return {@link SubscriptionInformation} from the provider
|
||||
* @throws RateLimitExceededException If rate-limited
|
||||
* @throws SubscriptionNotFoundException If the provided key was not found with the provider
|
||||
*/
|
||||
SubscriptionInformation getSubscriptionInformation(final String subscriptionId)
|
||||
throws RateLimitExceededException, SubscriptionNotFoundException;
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
|
||||
public class SubscriptionPaymentRequiredException extends SubscriptionException {
|
||||
|
||||
public SubscriptionPaymentRequiredException() {
|
||||
super(null, null);
|
||||
}
|
||||
|
||||
public SubscriptionPaymentRequiredException(String message) {
|
||||
super(null, message);
|
||||
}
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
|
||||
public class SubscriptionPaymentRequiresActionException extends SubscriptionInvalidArgumentsException {
|
||||
|
||||
public SubscriptionPaymentRequiresActionException(String message) {
|
||||
super(message, null);
|
||||
}
|
||||
|
||||
public SubscriptionPaymentRequiresActionException() {
|
||||
super(null, null);
|
||||
}
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
|
||||
public class SubscriptionProcessorConflictException extends SubscriptionException {
|
||||
|
||||
public SubscriptionProcessorConflictException() {
|
||||
super(null, null);
|
||||
}
|
||||
|
||||
public SubscriptionProcessorConflictException(final String message) {
|
||||
super(null, message);
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
|
||||
public class SubscriptionProcessorException extends SubscriptionException {
|
||||
|
||||
private final PaymentProvider processor;
|
||||
private final ChargeFailure chargeFailure;
|
||||
|
||||
public SubscriptionProcessorException(final PaymentProvider processor, final ChargeFailure chargeFailure) {
|
||||
super(null, null);
|
||||
this.processor = processor;
|
||||
this.chargeFailure = chargeFailure;
|
||||
}
|
||||
|
||||
public PaymentProvider getProcessor() {
|
||||
return processor;
|
||||
}
|
||||
|
||||
public ChargeFailure getChargeFailure() {
|
||||
return chargeFailure;
|
||||
}
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
|
||||
/**
|
||||
* Attempted to retrieve a receipt for a subscription that hasn't yet been charged or the invoice is in the open state
|
||||
*/
|
||||
public class SubscriptionReceiptRequestedForOpenPaymentException extends SubscriptionException {
|
||||
|
||||
public SubscriptionReceiptRequestedForOpenPaymentException() {
|
||||
super(null, null);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.util;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import java.util.concurrent.Executor;
|
||||
|
||||
public class ExecutorUtil {
|
||||
|
||||
private ExecutorUtil() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Submit all runnables to executorService and wait for them all to complete.
|
||||
* <p>
|
||||
* If any runnable completes exceptionally, after all runnables have completed the first exception will be thrown
|
||||
*
|
||||
* @param executor The executor to run runnables
|
||||
* @param runnables A collection of runnables to run
|
||||
*/
|
||||
public static void runAll(Executor executor, Collection<Runnable> runnables) {
|
||||
try {
|
||||
CompletableFuture.allOf(runnables
|
||||
.stream()
|
||||
.map(runnable -> CompletableFuture.runAsync(runnable, executor))
|
||||
.toArray(CompletableFuture[]::new))
|
||||
.join();
|
||||
} catch (CompletionException e) {
|
||||
final Throwable cause = e.getCause();
|
||||
// These exceptions should always be RuntimeExceptions because Runnable does not throw
|
||||
if (cause instanceof RuntimeException re) {
|
||||
throw re;
|
||||
} else {
|
||||
throw new IllegalStateException(cause);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+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={}",
|
||||
|
||||
+3
-1
@@ -22,7 +22,9 @@ import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
public class CertificateCommand extends Command {
|
||||
|
||||
private static final Set<Integer> RESERVED_CERTIFICATE_IDS = Set.of(
|
||||
0xdeadc357 // Reserved for testing; see https://github.com/signalapp/libsignal-client/pull/118
|
||||
// Reserved for testing in libsignal.
|
||||
0xdeadc357, // "dead cert", one considered revoked
|
||||
0x7357c357 // "test cert", one signed with a testing trust root
|
||||
);
|
||||
|
||||
public CertificateCommand() {
|
||||
|
||||
+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,
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.auth;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType;
|
||||
import static org.assertj.core.api.AssertionsForClassTypes.assertThatNoException;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.stream.StreamSupport;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.whispersystems.textsecuregcm.util.TestClock;
|
||||
|
||||
|
||||
class RedemptionRangeTest {
|
||||
|
||||
static List<Arguments> invalidCredentialTimeWindows() {
|
||||
final Duration max = RedemptionRange.MAX_REDEMPTION_DURATION;
|
||||
final Instant day0 = Instant.EPOCH;
|
||||
final Instant day1 = Instant.EPOCH.plus(Duration.ofDays(1));
|
||||
final Instant day2 = Instant.EPOCH.plus(Duration.ofDays(2));
|
||||
return List.of(
|
||||
Arguments.argumentSet("non-truncated start", Instant.ofEpochSecond(100), day0.plus(max),
|
||||
Instant.ofEpochSecond(100)),
|
||||
Arguments.argumentSet("non-truncated end", day0, Instant.ofEpochSecond(1).plus(max),
|
||||
Instant.ofEpochSecond(100)),
|
||||
Arguments.argumentSet("start too old", day0, day0.plus(max), day2),
|
||||
Arguments.argumentSet("end too far in the future", day2, day2.plus(max), day0),
|
||||
Arguments.argumentSet("end before start", day1, day0, day1),
|
||||
Arguments.argumentSet("window too big", day0, day0.plus(max).plus(Duration.ofDays(1)), day1)
|
||||
);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void invalidCredentialTimeWindows(final Instant requestRedemptionStart, final Instant requestRedemptionEnd,
|
||||
final Instant now) {
|
||||
final Clock clock = TestClock.pinned(now);
|
||||
assertThatExceptionOfType(IllegalArgumentException.class)
|
||||
.isThrownBy(() -> RedemptionRange.inclusive(clock, requestRedemptionStart, requestRedemptionEnd));
|
||||
}
|
||||
|
||||
@Test
|
||||
void allowUpToMax() {
|
||||
final Instant now = Instant.EPOCH.plus(Duration.ofDays(1)).plus(Duration.ofSeconds(100));
|
||||
final Instant today = now.truncatedTo(ChronoUnit.DAYS);
|
||||
final Clock clock = TestClock.pinned(now);
|
||||
for (Duration d = Duration.ofDays(0);
|
||||
d.compareTo(RedemptionRange.MAX_REDEMPTION_DURATION) <= 0;
|
||||
d = d.plus(Duration.ofDays(1))) {
|
||||
final Duration fd = d;
|
||||
assertThatNoException().isThrownBy(() -> RedemptionRange.inclusive(clock, today, today.plus(fd)));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void allowBackwardsSkew() {
|
||||
final Instant now = Instant.EPOCH.plus(Duration.ofDays(1)).plus(Duration.ofSeconds(100));
|
||||
final Instant yesterday = now.minus(Duration.ofDays(1)).truncatedTo(ChronoUnit.DAYS);
|
||||
final Clock clock = TestClock.pinned(now);
|
||||
assertThatNoException().isThrownBy(() ->
|
||||
RedemptionRange.inclusive(clock, yesterday, yesterday.plus(RedemptionRange.MAX_REDEMPTION_DURATION)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void allowForwardsSkew() {
|
||||
final Instant now = Instant.EPOCH.plus(Duration.ofDays(1)).plus(Duration.ofSeconds(100));
|
||||
final Instant tomorrow = now.plus(Duration.ofDays(1)).truncatedTo(ChronoUnit.DAYS);
|
||||
final Clock clock = TestClock.pinned(now);
|
||||
assertThatNoException().isThrownBy(() ->
|
||||
RedemptionRange.inclusive(clock, tomorrow, tomorrow.plus(RedemptionRange.MAX_REDEMPTION_DURATION)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void inclusiveRange() {
|
||||
final Instant now = Instant.EPOCH.plus(Duration.ofDays(1)).plus(Duration.ofSeconds(100));
|
||||
final Instant today = now.truncatedTo(ChronoUnit.DAYS);
|
||||
final Clock clock = TestClock.pinned(now);
|
||||
for (int numDays = 0; numDays < 7; numDays++) {
|
||||
final RedemptionRange range = RedemptionRange.inclusive(clock, today, today.plus(Duration.ofDays(numDays)));
|
||||
final List<Instant> instants = StreamSupport.stream(range.spliterator(), false).toList();
|
||||
assertThat(instants.size()).isEqualTo(numDays + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
+52
-65
@@ -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;
|
||||
@@ -28,15 +29,12 @@ import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.stream.Stream;
|
||||
import org.assertj.core.api.Assertions;
|
||||
import org.assertj.core.api.ThrowableAssert;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.EnumSource;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.junitpioneer.jupiter.cartesian.CartesianTest;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
@@ -54,9 +52,11 @@ import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialRequestContext;
|
||||
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.RedemptionRange;
|
||||
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;
|
||||
@@ -69,18 +69,20 @@ import org.whispersystems.textsecuregcm.util.TestRandomUtil;
|
||||
|
||||
public class BackupAuthManagerTest {
|
||||
|
||||
private static final Instant NOW = Instant.now();
|
||||
|
||||
private final UUID aci = UUID.randomUUID();
|
||||
private final byte[] messagesBackupKey = TestRandomUtil.nextBytes(32);
|
||||
private final byte[] mediaBackupKey = TestRandomUtil.nextBytes(32);
|
||||
private final ServerSecretParams receiptParams = ServerSecretParams.generate();
|
||||
private final TestClock clock = TestClock.now();
|
||||
private final TestClock clock = TestClock.pinned(NOW);
|
||||
private final BackupAuthTestUtil backupAuthTestUtil = new BackupAuthTestUtil(clock);
|
||||
private final AccountsManager accountsManager = mock(AccountsManager.class);
|
||||
private final RedeemedReceiptsManager redeemedReceiptsManager = mock(RedeemedReceiptsManager.class);
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
clock.unpin();
|
||||
clock.pin(NOW);
|
||||
reset(accountsManager);
|
||||
reset(redeemedReceiptsManager);
|
||||
}
|
||||
@@ -179,13 +181,13 @@ public class BackupAuthManagerTest {
|
||||
final BackupAuthCredentialRequestContext requestContext =
|
||||
BackupAuthCredentialRequestContext.create(backupKey, aci);
|
||||
|
||||
final Instant start = clock.instant().truncatedTo(ChronoUnit.DAYS);
|
||||
final List<BackupAuthManager.Credential> creds = authManager.getBackupAuthCredentials(account,
|
||||
credentialType, start, start.plus(Duration.ofDays(1))).join();
|
||||
final RedemptionRange range = range(Duration.ofDays(1));
|
||||
final List<BackupAuthManager.Credential> creds =
|
||||
authManager.getBackupAuthCredentials(account, credentialType, range(Duration.ofDays(1))).join();
|
||||
|
||||
assertThat(creds).hasSize(2);
|
||||
assertThat(requestContext
|
||||
.receiveResponse(creds.getFirst().credential(), start, backupAuthTestUtil.params.getPublicParams())
|
||||
.receiveResponse(creds.getFirst().credential(), range.iterator().next(), backupAuthTestUtil.params.getPublicParams())
|
||||
.getBackupLevel())
|
||||
.isEqualTo(BackupLevel.PAID);
|
||||
}
|
||||
@@ -202,10 +204,7 @@ public class BackupAuthManagerTest {
|
||||
.mediaCredential(backupAuthTestUtil.getRequest(mediaBackupKey, aci))
|
||||
.build();
|
||||
|
||||
assertThat(authManager.getBackupAuthCredentials(account,
|
||||
credentialType,
|
||||
clock.instant().truncatedTo(ChronoUnit.DAYS),
|
||||
clock.instant().plus(Duration.ofDays(1)).truncatedTo(ChronoUnit.DAYS)).join())
|
||||
assertThat(authManager.getBackupAuthCredentials(account, credentialType, range(Duration.ofDays(1))).join())
|
||||
.hasSize(2);
|
||||
}
|
||||
|
||||
@@ -217,10 +216,8 @@ public class BackupAuthManagerTest {
|
||||
final Account account = new MockAccountBuilder().build();
|
||||
|
||||
assertThatExceptionOfType(StatusRuntimeException.class)
|
||||
.isThrownBy(() -> authManager.getBackupAuthCredentials(account,
|
||||
credentialType,
|
||||
clock.instant().truncatedTo(ChronoUnit.DAYS),
|
||||
clock.instant().plus(Duration.ofDays(1)).truncatedTo(ChronoUnit.DAYS)).join())
|
||||
.isThrownBy(() ->
|
||||
authManager.getBackupAuthCredentials(account, credentialType, range(Duration.ofDays(1))).join())
|
||||
.extracting(ex -> ex.getStatus().getCode())
|
||||
.isEqualTo(Status.Code.NOT_FOUND);
|
||||
}
|
||||
@@ -244,12 +241,11 @@ public class BackupAuthManagerTest {
|
||||
.messagesCredential(backupAuthTestUtil.getRequest(messagesBackupKey, aci))
|
||||
.build();
|
||||
|
||||
final Instant start = clock.instant().truncatedTo(ChronoUnit.DAYS);
|
||||
final List<BackupAuthManager.Credential> creds = authManager.getBackupAuthCredentials(account,
|
||||
credentialType, start, start.plus(Duration.ofDays(7))).join();
|
||||
credentialType, range(Duration.ofDays(7))).join();
|
||||
|
||||
assertThat(creds).hasSize(8);
|
||||
Instant redemptionTime = start;
|
||||
Instant redemptionTime = clock.instant().truncatedTo(ChronoUnit.DAYS);
|
||||
for (BackupAuthManager.Credential cred : creds) {
|
||||
assertThat(requestContext
|
||||
.receiveResponse(cred.credential(), redemptionTime, backupAuthTestUtil.params.getPublicParams())
|
||||
@@ -260,51 +256,10 @@ public class BackupAuthManagerTest {
|
||||
}
|
||||
}
|
||||
|
||||
static Stream<Arguments> invalidCredentialTimeWindows() {
|
||||
final Duration max = Duration.ofDays(7);
|
||||
final Instant day0 = Instant.EPOCH;
|
||||
final Instant day1 = Instant.EPOCH.plus(Duration.ofDays(1));
|
||||
return Stream.of(
|
||||
// non-truncated start
|
||||
Arguments.of(Instant.ofEpochSecond(100), day0.plus(max), Instant.ofEpochSecond(100)),
|
||||
// non-truncated end
|
||||
Arguments.of(day0, Instant.ofEpochSecond(1).plus(max), Instant.ofEpochSecond(100)),
|
||||
// start to old
|
||||
Arguments.of(day0, day0.plus(max), day1),
|
||||
// end to new
|
||||
Arguments.of(day1, day1.plus(max), day0),
|
||||
// end before start
|
||||
Arguments.of(day1, day0, day1),
|
||||
// window too big
|
||||
Arguments.of(day0, day0.plus(max).plus(Duration.ofDays(1)), Instant.ofEpochSecond(100))
|
||||
);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void invalidCredentialTimeWindows(final Instant requestRedemptionStart, final Instant requestRedemptionEnd,
|
||||
final Instant now) {
|
||||
final BackupAuthManager authManager = create();
|
||||
|
||||
final Account account = new MockAccountBuilder()
|
||||
.messagesCredential(backupAuthTestUtil.getRequest(messagesBackupKey, aci))
|
||||
.mediaCredential(backupAuthTestUtil.getRequest(mediaBackupKey, aci))
|
||||
.build();
|
||||
|
||||
clock.pin(now);
|
||||
assertThatExceptionOfType(StatusRuntimeException.class)
|
||||
.isThrownBy(
|
||||
() -> authManager.getBackupAuthCredentials(account, BackupCredentialType.MESSAGES, requestRedemptionStart, requestRedemptionEnd).join())
|
||||
.extracting(ex -> ex.getStatus().getCode())
|
||||
.isEqualTo(Status.Code.INVALID_ARGUMENT);
|
||||
}
|
||||
|
||||
@Test
|
||||
void expiringBackupPayment() throws VerificationFailedException {
|
||||
clock.pin(Instant.ofEpochSecond(1));
|
||||
final Instant day0 = Instant.EPOCH;
|
||||
final Instant day4 = Instant.EPOCH.plus(Duration.ofDays(4));
|
||||
final Instant dayMax = day0.plus(BackupAuthManager.MAX_REDEMPTION_DURATION);
|
||||
|
||||
final BackupAuthManager authManager = create();
|
||||
|
||||
@@ -314,8 +269,11 @@ public class BackupAuthManagerTest {
|
||||
.backupVoucher(new Account.BackupVoucher(201, day4))
|
||||
.build();
|
||||
|
||||
final List<BackupAuthManager.Credential> creds = authManager.getBackupAuthCredentials(account, BackupCredentialType.MESSAGES, day0, dayMax).join();
|
||||
Instant redemptionTime = day0;
|
||||
final List<BackupAuthManager.Credential> creds = authManager.getBackupAuthCredentials(
|
||||
account,
|
||||
BackupCredentialType.MESSAGES,
|
||||
range(RedemptionRange.MAX_REDEMPTION_DURATION)).join();
|
||||
Instant redemptionTime = Instant.EPOCH;
|
||||
final BackupAuthCredentialRequestContext requestContext = BackupAuthCredentialRequestContext.create(
|
||||
messagesBackupKey, aci);
|
||||
for (int i = 0; i < creds.size(); i++) {
|
||||
@@ -353,7 +311,7 @@ public class BackupAuthManagerTest {
|
||||
when(accountsManager.updateAsync(any(), any())).thenReturn(CompletableFuture.completedFuture(updated));
|
||||
|
||||
clock.pin(day2.plus(Duration.ofSeconds(1)));
|
||||
assertThat(authManager.getBackupAuthCredentials(account, BackupCredentialType.MESSAGES, day2, day2.plus(Duration.ofDays(7))).join())
|
||||
assertThat(authManager.getBackupAuthCredentials(account, BackupCredentialType.MESSAGES, range(Duration.ofDays(7))).join())
|
||||
.hasSize(8);
|
||||
|
||||
@SuppressWarnings("unchecked") final ArgumentCaptor<Consumer<Account>> accountUpdater = ArgumentCaptor.forClass(
|
||||
@@ -511,6 +469,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(
|
||||
@@ -598,7 +576,7 @@ public class BackupAuthManagerTest {
|
||||
|
||||
private class MockAccountBuilder {
|
||||
|
||||
private Account account = mock(Account.class);
|
||||
private final Account account = mock(Account.class);
|
||||
|
||||
MockAccountBuilder() {
|
||||
when(account.getUuid()).thenReturn(aci);
|
||||
@@ -643,11 +621,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);
|
||||
@@ -655,4 +637,9 @@ public class BackupAuthManagerTest {
|
||||
.thenReturn(rateLimitPaidMediaBackupId ? denyLimiter : allowLimiter);
|
||||
return limiters;
|
||||
}
|
||||
|
||||
private RedemptionRange range(Duration length) {
|
||||
final Instant start = clock.instant().truncatedTo(ChronoUnit.DAYS);
|
||||
return RedemptionRange.inclusive(clock, start, start.plus(length));
|
||||
}
|
||||
}
|
||||
+4
-1
@@ -21,6 +21,7 @@ import org.signal.libsignal.zkgroup.backups.BackupAuthCredentialRequest;
|
||||
import org.signal.libsignal.zkgroup.backups.BackupAuthCredentialRequestContext;
|
||||
import org.signal.libsignal.zkgroup.backups.BackupCredentialType;
|
||||
import org.signal.libsignal.zkgroup.backups.BackupLevel;
|
||||
import org.whispersystems.textsecuregcm.auth.RedemptionRange;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
|
||||
@@ -73,6 +74,8 @@ public class BackupAuthTestUtil {
|
||||
case FREE -> null;
|
||||
case PAID -> new Account.BackupVoucher(201L, redemptionEnd.plus(1, ChronoUnit.SECONDS));
|
||||
});
|
||||
return issuer.getBackupAuthCredentials(account, credentialType, redemptionStart, redemptionEnd).join();
|
||||
final RedemptionRange redemptionRange;
|
||||
redemptionRange = RedemptionRange.inclusive(clock, redemptionStart, redemptionEnd);
|
||||
return issuer.getBackupAuthCredentials(account, credentialType, redemptionRange).join();
|
||||
}
|
||||
}
|
||||
+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();
|
||||
|
||||
+25
-2
@@ -64,6 +64,7 @@ import org.signal.libsignal.zkgroup.receipts.ServerZkReceiptOperations;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedBackupUser;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
|
||||
import org.whispersystems.textsecuregcm.auth.RedemptionRange;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupAuthManager;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupAuthTestUtil;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupManager;
|
||||
@@ -182,6 +183,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();
|
||||
@@ -301,14 +323,15 @@ public class ArchiveControllerTest {
|
||||
public void getCredentials() {
|
||||
final Instant start = Instant.now().truncatedTo(ChronoUnit.DAYS);
|
||||
final Instant end = start.plus(Duration.ofDays(1));
|
||||
final RedemptionRange expectedRange = RedemptionRange.inclusive(Clock.systemUTC(), start, end);
|
||||
|
||||
final Map<BackupCredentialType, List<BackupAuthManager.Credential>> expectedCredentialsByType =
|
||||
EnumMapUtil.toEnumMap(BackupCredentialType.class, credentialType -> backupAuthTestUtil.getCredentials(
|
||||
BackupLevel.PAID, backupAuthTestUtil.getRequest(messagesBackupKey, aci), credentialType, start, end));
|
||||
|
||||
expectedCredentialsByType.forEach((credentialType, expectedCredentials) ->
|
||||
when(backupAuthManager.getBackupAuthCredentials(any(), eq(credentialType), eq(start), eq(end))).thenReturn(
|
||||
CompletableFuture.completedFuture(expectedCredentials)));
|
||||
when(backupAuthManager.getBackupAuthCredentials(any(), eq(credentialType), eq(expectedRange)))
|
||||
.thenReturn(CompletableFuture.completedFuture(expectedCredentials)));
|
||||
|
||||
final ArchiveController.BackupAuthCredentialsResponse credentialResponse = resources.getJerseyTest()
|
||||
.target("v1/archives/auth")
|
||||
|
||||
+4
-4
@@ -116,8 +116,8 @@ class DonationControllerTest {
|
||||
when(receiptCredentialPresentation.getReceiptExpirationTime()).thenReturn(receiptExpiration);
|
||||
when(redeemedReceiptsManager.put(same(receiptSerial), eq(receiptExpiration), eq(receiptLevel), eq(AuthHelper.VALID_UUID))).thenReturn(
|
||||
CompletableFuture.completedFuture(Boolean.TRUE));
|
||||
when(accountsManager.getByAccountIdentifierAsync(eq(AuthHelper.VALID_UUID))).thenReturn(
|
||||
CompletableFuture.completedFuture(Optional.of(AuthHelper.VALID_ACCOUNT)));
|
||||
when(accountsManager.getByAccountIdentifier(eq(AuthHelper.VALID_UUID)))
|
||||
.thenReturn(Optional.of(AuthHelper.VALID_ACCOUNT));
|
||||
|
||||
RedeemReceiptRequest request = new RedeemReceiptRequest(presentation, true, true);
|
||||
Response response = resources.getJerseyTest()
|
||||
@@ -140,8 +140,8 @@ class DonationControllerTest {
|
||||
when(receiptCredentialPresentation.getReceiptExpirationTime()).thenReturn(receiptExpiration);
|
||||
when(redeemedReceiptsManager.put(same(receiptSerial), eq(receiptExpiration), eq(receiptLevel), eq(AuthHelper.VALID_UUID))).thenReturn(
|
||||
CompletableFuture.completedFuture(Boolean.FALSE));
|
||||
when(accountsManager.getByAccountIdentifierAsync(eq(AuthHelper.VALID_UUID))).thenReturn(
|
||||
CompletableFuture.completedFuture(Optional.of(AuthHelper.VALID_ACCOUNT)));
|
||||
when(accountsManager.getByAccountIdentifier(eq(AuthHelper.VALID_UUID)))
|
||||
.thenReturn(Optional.of(AuthHelper.VALID_ACCOUNT));
|
||||
|
||||
RedeemReceiptRequest request = new RedeemReceiptRequest(presentation, true, true);
|
||||
Response response = resources.getJerseyTest()
|
||||
|
||||
+55
-49
@@ -21,7 +21,6 @@ import static org.whispersystems.textsecuregcm.util.AttributeValues.n;
|
||||
import static org.whispersystems.textsecuregcm.util.AttributeValues.s;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.stripe.exception.ApiException;
|
||||
import com.stripe.model.PaymentIntent;
|
||||
import io.dropwizard.auth.AuthValueFactoryProvider;
|
||||
import io.dropwizard.testing.junit5.DropwizardExtensionsSupport;
|
||||
@@ -42,7 +41,6 @@ import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.stream.Stream;
|
||||
import org.assertj.core.api.InstanceOfAssertFactories;
|
||||
@@ -65,20 +63,23 @@ 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;
|
||||
import org.whispersystems.textsecuregcm.storage.SubscriptionException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionChargeFailurePaymentRequiredException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionException;
|
||||
import org.whispersystems.textsecuregcm.storage.SubscriptionManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Subscriptions;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.AppleAppStoreManager;
|
||||
@@ -94,6 +95,13 @@ import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentStatus;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.ProcessorCustomer;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.StripeManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidArgumentsException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionNotFoundException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentRequiredException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentRequiresActionException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorConflictException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptRequestedForOpenPaymentException;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
|
||||
import org.whispersystems.textsecuregcm.util.MockUtils;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
@@ -106,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);
|
||||
@@ -123,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()
|
||||
@@ -148,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()))
|
||||
@@ -337,7 +351,7 @@ class SubscriptionControllerTest {
|
||||
|
||||
when(BRAINTREE_MANAGER.captureOneTimePayment(anyString(), anyString(), anyString(), anyString(), anyLong(),
|
||||
anyLong(), any()))
|
||||
.thenReturn(CompletableFuture.failedFuture(new SubscriptionException.ProcessorException(PaymentProvider.BRAINTREE,
|
||||
.thenReturn(CompletableFuture.failedFuture(new SubscriptionProcessorException(PaymentProvider.BRAINTREE,
|
||||
new ChargeFailure("2046", "Declined", null, null, null))));
|
||||
|
||||
final Response response = RESOURCE_EXTENSION.target("/v1/subscription/boost/paypal/confirm")
|
||||
@@ -399,9 +413,9 @@ class SubscriptionControllerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void createSubscriptionSuccess() {
|
||||
void createSubscriptionSuccess() throws SubscriptionException {
|
||||
when(STRIPE_MANAGER.createSubscription(any(), any(), anyLong(), anyLong()))
|
||||
.thenReturn(CompletableFuture.completedFuture(mock(CustomerAwareSubscriptionPaymentProcessor.SubscriptionId.class)));
|
||||
.thenReturn(mock(CustomerAwareSubscriptionPaymentProcessor.SubscriptionId.class));
|
||||
|
||||
final String level = String.valueOf(levelId);
|
||||
final String idempotencyKey = UUID.randomUUID().toString();
|
||||
@@ -414,10 +428,10 @@ class SubscriptionControllerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void createSubscriptionProcessorDeclined() {
|
||||
void createSubscriptionProcessorDeclined() throws SubscriptionException {
|
||||
when(STRIPE_MANAGER.createSubscription(any(), any(), anyLong(), anyLong()))
|
||||
.thenReturn(CompletableFuture.failedFuture(new SubscriptionException.ProcessorException(PaymentProvider.STRIPE,
|
||||
new ChargeFailure("card_declined", "Insufficient funds", null, null, null))));
|
||||
.thenThrow(new SubscriptionProcessorException(PaymentProvider.STRIPE,
|
||||
new ChargeFailure("card_declined", "Insufficient funds", null, null, null)));
|
||||
|
||||
final String level = String.valueOf(levelId);
|
||||
final String idempotencyKey = UUID.randomUUID().toString();
|
||||
@@ -489,11 +503,10 @@ class SubscriptionControllerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void stripePaymentIntentRequiresAction() {
|
||||
final ApiException stripeException = new ApiException("Payment intent requires action",
|
||||
UUID.randomUUID().toString(), "subscription_payment_intent_requires_action", 400, new Exception());
|
||||
void stripePaymentIntentRequiresAction()
|
||||
throws SubscriptionInvalidArgumentsException, SubscriptionProcessorException {
|
||||
when(STRIPE_MANAGER.createSubscription(any(), any(), anyLong(), anyLong()))
|
||||
.thenReturn(CompletableFuture.failedFuture(new CompletionException(stripeException)));
|
||||
.thenThrow(new SubscriptionPaymentRequiresActionException());
|
||||
|
||||
final String level = String.valueOf(levelId);
|
||||
final String idempotencyKey = UUID.randomUUID().toString();
|
||||
@@ -624,7 +637,7 @@ class SubscriptionControllerTest {
|
||||
final ProcessorCustomer customer = new ProcessorCustomer(
|
||||
customerId, PaymentProvider.STRIPE);
|
||||
when(STRIPE_MANAGER.createCustomer(any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(customer));
|
||||
.thenReturn(customer);
|
||||
|
||||
final Map<String, AttributeValue> dynamoItemWithProcessorCustomer = new HashMap<>(dynamoItem);
|
||||
dynamoItemWithProcessorCustomer.put(Subscriptions.KEY_PROCESSOR_ID_CUSTOMER_ID,
|
||||
@@ -638,7 +651,7 @@ class SubscriptionControllerTest {
|
||||
|
||||
final String clientSecret = "some-client-secret";
|
||||
when(STRIPE_MANAGER.createPaymentMethodSetupToken(customerId))
|
||||
.thenReturn(CompletableFuture.completedFuture(clientSecret));
|
||||
.thenReturn(clientSecret);
|
||||
|
||||
final SubscriptionController.CreatePaymentMethodResponse createPaymentMethodResponse = RESOURCE_EXTENSION
|
||||
.target(String.format("/v1/subscription/%s/create_payment_method", subscriberId))
|
||||
@@ -687,7 +700,8 @@ class SubscriptionControllerTest {
|
||||
"35, M3",
|
||||
"201, M4",
|
||||
})
|
||||
void setSubscriptionLevel(long levelId, String expectedProcessorId) {
|
||||
void setSubscriptionLevel(long levelId, String expectedProcessorId)
|
||||
throws SubscriptionProcessorConflictException, SubscriptionProcessorException {
|
||||
// set up record
|
||||
final byte[] subscriberUserAndKey = new byte[32];
|
||||
Arrays.fill(subscriberUserAndKey, (byte) 1);
|
||||
@@ -711,8 +725,7 @@ class SubscriptionControllerTest {
|
||||
.thenReturn(CompletableFuture.completedFuture(Subscriptions.GetResult.found(record)));
|
||||
|
||||
when(BRAINTREE_MANAGER.createSubscription(any(), any(), anyLong(), anyLong()))
|
||||
.thenReturn(CompletableFuture.completedFuture(new CustomerAwareSubscriptionPaymentProcessor.SubscriptionId(
|
||||
"subscription")));
|
||||
.thenReturn(new CustomerAwareSubscriptionPaymentProcessor.SubscriptionId("subscription"));
|
||||
when(SUBSCRIPTIONS.subscriptionCreated(any(), any(), any(), anyLong()))
|
||||
.thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
@@ -734,7 +747,8 @@ class SubscriptionControllerTest {
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void setSubscriptionLevelExistingSubscription(final String existingCurrency, final long existingLevel,
|
||||
final String requestCurrency, final long requestLevel, final boolean expectUpdate) {
|
||||
final String requestCurrency, final long requestLevel, final boolean expectUpdate)
|
||||
throws SubscriptionProcessorConflictException, SubscriptionProcessorException {
|
||||
|
||||
// set up record
|
||||
final byte[] subscriberUserAndKey = new byte[32];
|
||||
@@ -761,17 +775,14 @@ class SubscriptionControllerTest {
|
||||
.thenReturn(CompletableFuture.completedFuture(Subscriptions.GetResult.found(record)));
|
||||
|
||||
final Object subscriptionObj = new Object();
|
||||
when(BRAINTREE_MANAGER.getSubscription(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(subscriptionObj));
|
||||
when(BRAINTREE_MANAGER.getSubscription(any())).thenReturn(subscriptionObj);
|
||||
when(BRAINTREE_MANAGER.getLevelAndCurrencyForSubscription(subscriptionObj))
|
||||
.thenReturn(CompletableFuture.completedFuture(
|
||||
new CustomerAwareSubscriptionPaymentProcessor.LevelAndCurrency(existingLevel, existingCurrency)));
|
||||
.thenReturn(new CustomerAwareSubscriptionPaymentProcessor.LevelAndCurrency(existingLevel, existingCurrency));
|
||||
final String updatedSubscriptionId = "updatedSubscriptionId";
|
||||
|
||||
if (expectUpdate) {
|
||||
when(BRAINTREE_MANAGER.updateSubscription(any(), any(), anyLong(), anyString()))
|
||||
.thenReturn(CompletableFuture.completedFuture(new CustomerAwareSubscriptionPaymentProcessor.SubscriptionId(
|
||||
updatedSubscriptionId)));
|
||||
.thenReturn(new CustomerAwareSubscriptionPaymentProcessor.SubscriptionId(updatedSubscriptionId));
|
||||
when(SUBSCRIPTIONS.subscriptionLevelChanged(any(), any(), anyLong(), anyString()))
|
||||
.thenReturn(CompletableFuture.completedFuture(null));
|
||||
}
|
||||
@@ -836,11 +847,9 @@ class SubscriptionControllerTest {
|
||||
.thenReturn(CompletableFuture.completedFuture(Subscriptions.GetResult.found(record)));
|
||||
|
||||
final Object subscriptionObj = new Object();
|
||||
when(BRAINTREE_MANAGER.getSubscription(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(subscriptionObj));
|
||||
when(BRAINTREE_MANAGER.getSubscription(any())).thenReturn(subscriptionObj);
|
||||
when(BRAINTREE_MANAGER.getLevelAndCurrencyForSubscription(subscriptionObj))
|
||||
.thenReturn(CompletableFuture.completedFuture(
|
||||
new CustomerAwareSubscriptionPaymentProcessor.LevelAndCurrency(201, "usd")));
|
||||
.thenReturn(new CustomerAwareSubscriptionPaymentProcessor.LevelAndCurrency(201, "usd"));
|
||||
|
||||
// Try to change from a backup subscription (201) to a donation subscription (5)
|
||||
final Response response = RESOURCE_EXTENSION
|
||||
@@ -857,7 +866,8 @@ class SubscriptionControllerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void setAppStoreTransactionId() {
|
||||
public void setAppStoreTransactionId()
|
||||
throws SubscriptionInvalidArgumentsException, SubscriptionPaymentRequiredException, RateLimitExceededException, SubscriptionNotFoundException {
|
||||
final String originalTxId = "aTxId";
|
||||
final byte[] subscriberUserAndKey = new byte[32];
|
||||
Arrays.fill(subscriberUserAndKey, (byte) 1);
|
||||
@@ -877,7 +887,7 @@ class SubscriptionControllerTest {
|
||||
.thenReturn(CompletableFuture.completedFuture(Subscriptions.GetResult.found(record)));
|
||||
|
||||
when(APPSTORE_MANAGER.validateTransaction(eq(originalTxId)))
|
||||
.thenReturn(CompletableFuture.completedFuture(99L));
|
||||
.thenReturn(99L);
|
||||
|
||||
when(SUBSCRIPTIONS.setIapPurchase(any(), any(), anyString(), anyLong(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(null));
|
||||
@@ -900,7 +910,7 @@ class SubscriptionControllerTest {
|
||||
|
||||
|
||||
@Test
|
||||
public void setPlayPurchaseToken() {
|
||||
public void setPlayPurchaseToken() throws RateLimitExceededException, SubscriptionException {
|
||||
final String purchaseToken = "aPurchaseToken";
|
||||
final byte[] subscriberUserAndKey = new byte[32];
|
||||
Arrays.fill(subscriberUserAndKey, (byte) 1);
|
||||
@@ -920,8 +930,7 @@ class SubscriptionControllerTest {
|
||||
|
||||
final GooglePlayBillingManager.ValidatedToken validatedToken = mock(GooglePlayBillingManager.ValidatedToken.class);
|
||||
when(validatedToken.getLevel()).thenReturn(99L);
|
||||
when(validatedToken.acknowledgePurchase()).thenReturn(CompletableFuture.completedFuture(null));
|
||||
when(PLAY_MANAGER.validateToken(eq(purchaseToken))).thenReturn(CompletableFuture.completedFuture(validatedToken));
|
||||
when(PLAY_MANAGER.validateToken(eq(purchaseToken))).thenReturn(validatedToken);
|
||||
|
||||
when(SUBSCRIPTIONS.setIapPurchase(any(), any(), anyString(), anyLong(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(null));
|
||||
@@ -943,7 +952,7 @@ class SubscriptionControllerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void replacePlayPurchaseToken() {
|
||||
public void replacePlayPurchaseToken() throws RateLimitExceededException, SubscriptionException {
|
||||
final String oldPurchaseToken = "oldPurchaseToken";
|
||||
final String newPurchaseToken = "newPurchaseToken";
|
||||
final byte[] subscriberUserAndKey = new byte[32];
|
||||
@@ -965,11 +974,8 @@ class SubscriptionControllerTest {
|
||||
|
||||
final GooglePlayBillingManager.ValidatedToken validatedToken = mock(GooglePlayBillingManager.ValidatedToken.class);
|
||||
when(validatedToken.getLevel()).thenReturn(99L);
|
||||
when(validatedToken.acknowledgePurchase()).thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
when(PLAY_MANAGER.validateToken(eq(newPurchaseToken))).thenReturn(CompletableFuture.completedFuture(validatedToken));
|
||||
when(PLAY_MANAGER.cancelAllActiveSubscriptions(eq(oldPurchaseToken)))
|
||||
.thenReturn(CompletableFuture.completedFuture(null));
|
||||
when(PLAY_MANAGER.validateToken(eq(newPurchaseToken))).thenReturn(validatedToken);
|
||||
|
||||
when(SUBSCRIPTIONS.setIapPurchase(any(), any(), anyString(), anyLong(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(null));
|
||||
@@ -993,7 +999,8 @@ class SubscriptionControllerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void createReceiptChargeFailure() throws InvalidInputException, VerificationFailedException {
|
||||
void createReceiptChargeFailure()
|
||||
throws InvalidInputException, VerificationFailedException, SubscriptionException {
|
||||
final byte[] subscriberUserAndKey = new byte[32];
|
||||
Arrays.fill(subscriberUserAndKey, (byte) 1);
|
||||
final String subscriberId = Base64.getEncoder().encodeToString(subscriberUserAndKey);
|
||||
@@ -1009,9 +1016,9 @@ class SubscriptionControllerTest {
|
||||
b(new ProcessorCustomer("customer", PaymentProvider.STRIPE).toDynamoBytes()),
|
||||
Subscriptions.KEY_SUBSCRIPTION_ID, s("subscriptionId"))))));
|
||||
when(STRIPE_MANAGER.getReceiptItem(any()))
|
||||
.thenReturn(CompletableFuture.failedFuture(new SubscriptionException.ChargeFailurePaymentRequired(
|
||||
.thenThrow(new SubscriptionChargeFailurePaymentRequiredException(
|
||||
PaymentProvider.STRIPE,
|
||||
new ChargeFailure("card_declined", "Insufficient funds", null, null, null))));
|
||||
new ChargeFailure("card_declined", "Insufficient funds", null, null, null)));
|
||||
|
||||
final ReceiptCredentialRequest receiptRequest = new ClientZkReceiptOperations(
|
||||
ServerSecretParams.generate().getPublicParams()).createReceiptCredentialRequestContext(
|
||||
@@ -1033,7 +1040,7 @@ class SubscriptionControllerTest {
|
||||
@ParameterizedTest
|
||||
@CsvSource({"5, P45D", "201, P13D"})
|
||||
public void createReceiptCredential(long level, Duration expectedExpirationWindow)
|
||||
throws InvalidInputException, VerificationFailedException {
|
||||
throws InvalidInputException, VerificationFailedException, SubscriptionChargeFailurePaymentRequiredException, SubscriptionReceiptRequestedForOpenPaymentException {
|
||||
final byte[] subscriberUserAndKey = new byte[32];
|
||||
Arrays.fill(subscriberUserAndKey, (byte) 1);
|
||||
final String subscriberId = Base64.getEncoder().encodeToString(subscriberUserAndKey);
|
||||
@@ -1057,11 +1064,10 @@ class SubscriptionControllerTest {
|
||||
when(SUBSCRIPTIONS.get(any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(Subscriptions.GetResult.found(record)));
|
||||
when(BRAINTREE_MANAGER.getReceiptItem(subscriptionId)).thenReturn(
|
||||
CompletableFuture.completedFuture(new CustomerAwareSubscriptionPaymentProcessor.ReceiptItem(
|
||||
new CustomerAwareSubscriptionPaymentProcessor.ReceiptItem(
|
||||
"itemId",
|
||||
PaymentTime.periodStart(Instant.ofEpochSecond(10).plus(Duration.ofDays(1))),
|
||||
level
|
||||
)));
|
||||
level));
|
||||
when(ISSUED_RECEIPTS_MANAGER.recordIssuance(eq("itemId"), eq(PaymentProvider.BRAINTREE), eq(receiptRequest), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(null));
|
||||
when(ZK_OPS.issueReceiptCredential(any(), anyLong(), eq(level))).thenReturn(receiptCredentialResponse);
|
||||
@@ -1225,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);
|
||||
});
|
||||
|
||||
+3
-3
@@ -28,9 +28,7 @@ import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.junit.jupiter.params.provider.EnumSource;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.junitpioneer.jupiter.cartesian.CartesianTest;
|
||||
import org.mockito.Mock;
|
||||
import org.signal.chat.backup.BackupsGrpc;
|
||||
import org.signal.chat.backup.GetBackupAuthCredentialsRequest;
|
||||
@@ -51,6 +49,7 @@ import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialRequestContext;
|
||||
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.RedemptionRange;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupAuthManager;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupAuthTestUtil;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
@@ -193,6 +192,7 @@ class BackupsGrpcServiceTest extends SimpleBaseGrpcTest<BackupsGrpcService, Back
|
||||
void getCredentials() {
|
||||
final Instant start = Instant.now().truncatedTo(ChronoUnit.DAYS);
|
||||
final Instant end = start.plus(Duration.ofDays(1));
|
||||
final RedemptionRange expectedRange = RedemptionRange.inclusive(Clock.systemUTC(), start, end);
|
||||
|
||||
final Map<BackupCredentialType, List<BackupAuthManager.Credential>> expectedCredentialsByType =
|
||||
EnumMapUtil.toEnumMap(BackupCredentialType.class, credentialType -> backupAuthTestUtil.getCredentials(
|
||||
@@ -200,7 +200,7 @@ class BackupsGrpcServiceTest extends SimpleBaseGrpcTest<BackupsGrpcService, Back
|
||||
start, end));
|
||||
|
||||
expectedCredentialsByType.forEach((credentialType, expectedCredentials) ->
|
||||
when(backupAuthManager.getBackupAuthCredentials(any(), eq(credentialType), eq(start), eq(end)))
|
||||
when(backupAuthManager.getBackupAuthCredentials(any(), eq(credentialType), eq(expectedRange)))
|
||||
.thenReturn(CompletableFuture.completedFuture(expectedCredentials)));
|
||||
|
||||
final GetBackupAuthCredentialsResponse credentialResponse = authenticatedServiceStub().getBackupAuthCredentials(
|
||||
|
||||
-1
@@ -199,7 +199,6 @@ class MessagesAnonymousGrpcServiceTest extends
|
||||
.setServerTimestamp(CLOCK.millis())
|
||||
.setEphemeral(ephemeral)
|
||||
.setUrgent(urgent)
|
||||
.setStory(false)
|
||||
.setContent(ByteString.copyFrom(payload));
|
||||
|
||||
if (includeReportSpamToken) {
|
||||
|
||||
+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);
|
||||
}
|
||||
|
||||
}
|
||||
+3
-3
@@ -332,12 +332,12 @@ class FaultTolerantRedisClusterClientTest {
|
||||
final LettuceShardCircuitBreaker.ChannelCircuitBreakerHandler channelCircuitBreakerHandler =
|
||||
ctx.channel().pipeline().get(LettuceShardCircuitBreaker.ChannelCircuitBreakerHandler.class);
|
||||
|
||||
urisToChannelBreakers.computeIfAbsent(getRedisURI(ctx.channel()), ignored -> new HashSet<>())
|
||||
urisToChannelBreakers.computeIfAbsent(getRedisURI(remoteAddress), ignored -> new HashSet<>())
|
||||
.add(channelCircuitBreakerHandler);
|
||||
}
|
||||
|
||||
private static RedisURI getRedisURI(Channel channel) {
|
||||
final InetSocketAddress inetAddress = (InetSocketAddress) channel.remoteAddress();
|
||||
private static RedisURI getRedisURI(SocketAddress remoteAddress) {
|
||||
final InetSocketAddress inetAddress = (InetSocketAddress) remoteAddress;
|
||||
return RedisURI.create(inetAddress.getHostString(), inetAddress.getPort());
|
||||
}
|
||||
|
||||
|
||||
@@ -495,6 +495,10 @@ class AccountsTest {
|
||||
final UUID existingPni = UUID.randomUUID();
|
||||
final Account existingAccount = generateAccount(e164, existingUuid, existingPni, List.of(device));
|
||||
|
||||
// Backup vouchers should be carried over accross re-registration
|
||||
final Account.BackupVoucher bv = new Account.BackupVoucher(1, Instant.now().plus(Duration.ofDays(1)));
|
||||
existingAccount.setBackupVoucher(bv);
|
||||
|
||||
createAccount(existingAccount);
|
||||
|
||||
final byte[] usernameHash = TestRandomUtil.nextBytes(32);
|
||||
@@ -531,6 +535,8 @@ class AccountsTest {
|
||||
assertThat(result.getEncryptedUsername()).isEmpty();
|
||||
assertArrayEquals(result.getReservedUsernameHash().orElseThrow(), usernameHash);
|
||||
|
||||
assertThat(result.getBackupVoucher()).isEqualTo(bv);
|
||||
|
||||
// should keep the same usernameLink, now encryptedUsername should be set
|
||||
accounts.confirmUsernameHash(result, usernameHash, encryptedUsername).join();
|
||||
item = readAccount(existingUuid);
|
||||
|
||||
-1
@@ -181,7 +181,6 @@ public class ChangeNumberManagerTest {
|
||||
.setUpdatedPni(updatedPhoneNumberIdentifiersByAccount.get(account).toString())
|
||||
.setUrgent(true)
|
||||
.setEphemeral(false)
|
||||
.setStory(false)
|
||||
.build();
|
||||
|
||||
verify(messageSender).sendMessages(argThat(a -> a.getIdentifier(IdentityType.ACI).equals(aci)),
|
||||
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import com.apple.foundationdb.Database;
|
||||
import com.apple.foundationdb.FDB;
|
||||
import org.junit.jupiter.api.extension.BeforeAllCallback;
|
||||
import org.junit.jupiter.api.extension.ExtensionContext;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
public class FoundationDbClusterExtension implements BeforeAllCallback, ExtensionContext.Store.CloseableResource {
|
||||
|
||||
private FoundationDbDatabaseLifecycleManager[] databaseLifecycleManagers;
|
||||
private Database[] databases;
|
||||
|
||||
public FoundationDbClusterExtension(final int numInstances) {
|
||||
this.databaseLifecycleManagers = new FoundationDbDatabaseLifecycleManager[numInstances];
|
||||
this.databases = new Database[numInstances];
|
||||
}
|
||||
|
||||
@Override
|
||||
public void beforeAll(final ExtensionContext context) throws IOException {
|
||||
if (databaseLifecycleManagers[0] == null) {
|
||||
final String serviceContainerNamePrefix = System.getProperty("foundationDb.serviceContainerNamePrefix");
|
||||
|
||||
for (int i = 0; i < databaseLifecycleManagers.length; i++) {
|
||||
final FoundationDbDatabaseLifecycleManager databaseLifecycleManager = serviceContainerNamePrefix != null
|
||||
? new ServiceContainerFoundationDbDatabaseLifecycleManager(serviceContainerNamePrefix + i)
|
||||
: new TestcontainersFoundationDbDatabaseLifecycleManager();
|
||||
databaseLifecycleManager.initializeDatabase(FDB.selectAPIVersion(FoundationDbVersion.getFoundationDbApiVersion()));
|
||||
databaseLifecycleManagers[i] = databaseLifecycleManager;
|
||||
databases[i] = databaseLifecycleManager.getDatabase();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
public Database[] getDatabases() {
|
||||
return databases;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws Throwable {
|
||||
if (databaseLifecycleManagers[0] != null) {
|
||||
for (final FoundationDbDatabaseLifecycleManager databaseLifecycleManager : databaseLifecycleManagers) {
|
||||
databaseLifecycleManager.closeDatabase();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
-43
@@ -1,43 +0,0 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import com.apple.foundationdb.Database;
|
||||
import com.apple.foundationdb.FDB;
|
||||
import java.io.IOException;
|
||||
import org.junit.jupiter.api.extension.BeforeAllCallback;
|
||||
import org.junit.jupiter.api.extension.ExtensionContext;
|
||||
|
||||
public class FoundationDbExtension implements BeforeAllCallback, ExtensionContext.Store.CloseableResource {
|
||||
|
||||
private static FoundationDbDatabaseLifecycleManager databaseLifecycleManager;
|
||||
|
||||
@Override
|
||||
public void beforeAll(final ExtensionContext context) throws IOException {
|
||||
if (databaseLifecycleManager == null) {
|
||||
final String serviceContainerName = System.getProperty("foundationDb.serviceContainerName");
|
||||
|
||||
databaseLifecycleManager = serviceContainerName != null
|
||||
? new ServiceContainerFoundationDbDatabaseLifecycleManager(serviceContainerName)
|
||||
: new TestcontainersFoundationDbDatabaseLifecycleManager();
|
||||
|
||||
databaseLifecycleManager.initializeDatabase(FDB.selectAPIVersion(FoundationDbVersion.getFoundationDbApiVersion()));
|
||||
|
||||
context.getRoot().getStore(ExtensionContext.Namespace.GLOBAL).put(getClass().getName(), this);
|
||||
}
|
||||
}
|
||||
|
||||
public Database getDatabase() {
|
||||
return databaseLifecycleManager.getDatabase();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws Throwable {
|
||||
if (databaseLifecycleManager != null) {
|
||||
databaseLifecycleManager.closeDatabase();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
|
||||
public class FoundationDbTest {
|
||||
|
||||
@RegisterExtension
|
||||
static FoundationDbExtension FOUNDATION_DB_EXTENSION = new FoundationDbExtension();
|
||||
|
||||
@Test
|
||||
void setGetValue() {
|
||||
final byte[] key = "test".getBytes(StandardCharsets.UTF_8);
|
||||
final byte[] value = TestRandomUtil.nextBytes(16);
|
||||
|
||||
FOUNDATION_DB_EXTENSION.getDatabase().run(transaction -> {
|
||||
transaction.set(key, value);
|
||||
return null;
|
||||
});
|
||||
|
||||
final byte[] retrievedValue = FOUNDATION_DB_EXTENSION.getDatabase().run(transaction -> transaction.get(key).join());
|
||||
|
||||
assertArrayEquals(value, retrievedValue);
|
||||
}
|
||||
}
|
||||
+6
-4
@@ -152,15 +152,17 @@ class MessagesManagerTest {
|
||||
final boolean isEphemeral = ThreadLocalRandom.current().nextBoolean();
|
||||
final boolean isUrgent = ThreadLocalRandom.current().nextBoolean();
|
||||
|
||||
final Envelope prototypeExpectedMessage = Envelope.newBuilder()
|
||||
final Envelope.Builder expectedEnvelopeBuilder = Envelope.newBuilder()
|
||||
.setType(Envelope.Type.UNIDENTIFIED_SENDER)
|
||||
.setClientTimestamp(clientTimestamp)
|
||||
.setServerTimestamp(CLOCK.millis())
|
||||
.setStory(isStory)
|
||||
.setEphemeral(isEphemeral)
|
||||
.setUrgent(isUrgent)
|
||||
.setSharedMrmKey(ByteString.copyFrom(sharedMrmKey))
|
||||
.build();
|
||||
.setSharedMrmKey(ByteString.copyFrom(sharedMrmKey));
|
||||
if (isStory) {
|
||||
expectedEnvelopeBuilder.setStory(true);
|
||||
}
|
||||
final Envelope prototypeExpectedMessage = expectedEnvelopeBuilder.build();
|
||||
|
||||
assertEquals(expectedPresenceByAccountAndDeviceId,
|
||||
messagesManager.insertMultiRecipientMessage(multiRecipientMessage, resolvedRecipients, clientTimestamp, isStory, isEphemeral, isUrgent).join());
|
||||
|
||||
+231
-30
@@ -3,9 +3,11 @@ package org.whispersystems.textsecuregcm.storage.foundationdb;
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import com.apple.foundationdb.Database;
|
||||
import com.apple.foundationdb.KeyValue;
|
||||
import com.apple.foundationdb.async.AsyncUtil;
|
||||
import com.apple.foundationdb.tuple.Tuple;
|
||||
import com.apple.foundationdb.tuple.Versionstamp;
|
||||
import com.google.protobuf.ByteString;
|
||||
@@ -14,16 +16,21 @@ import java.io.UncheckedIOException;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneId;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
import java.util.stream.Stream;
|
||||
import io.dropwizard.util.DataSize;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.Timeout;
|
||||
@@ -35,7 +42,7 @@ import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.FoundationDbExtension;
|
||||
import org.whispersystems.textsecuregcm.storage.FoundationDbClusterExtension;
|
||||
import org.whispersystems.textsecuregcm.util.Conversions;
|
||||
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
|
||||
|
||||
@@ -43,7 +50,7 @@ import org.whispersystems.textsecuregcm.util.TestRandomUtil;
|
||||
class FoundationDbMessageStoreTest {
|
||||
|
||||
@RegisterExtension
|
||||
static FoundationDbExtension FOUNDATION_DB_EXTENSION = new FoundationDbExtension();
|
||||
static FoundationDbClusterExtension FOUNDATION_DB_EXTENSION = new FoundationDbClusterExtension(2);
|
||||
|
||||
private FoundationDbMessageStore foundationDbMessageStore;
|
||||
|
||||
@@ -52,7 +59,7 @@ class FoundationDbMessageStoreTest {
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
foundationDbMessageStore = new FoundationDbMessageStore(
|
||||
new Database[]{FOUNDATION_DB_EXTENSION.getDatabase()},
|
||||
FOUNDATION_DB_EXTENSION.getDatabases(),
|
||||
Executors.newVirtualThreadPerTaskExecutor(),
|
||||
CLOCK);
|
||||
}
|
||||
@@ -60,7 +67,7 @@ class FoundationDbMessageStoreTest {
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void insert(final long presenceUpdatedBeforeSeconds, final boolean ephemeral, final boolean expectMessagesInserted,
|
||||
final boolean expectVersionstampUpdated) {
|
||||
final boolean expectVersionstampUpdated, final boolean expectPresenceState) {
|
||||
final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID());
|
||||
final List<Byte> deviceIds = IntStream.range(Device.PRIMARY_ID, Device.PRIMARY_ID + 6)
|
||||
.mapToObj(i -> (byte) i)
|
||||
@@ -68,15 +75,19 @@ class FoundationDbMessageStoreTest {
|
||||
deviceIds.forEach(deviceId -> writePresenceKey(aci, deviceId, 1, presenceUpdatedBeforeSeconds));
|
||||
final Map<Byte, MessageProtos.Envelope> messagesByDeviceId = deviceIds.stream()
|
||||
.collect(Collectors.toMap(Function.identity(), _ -> generateRandomMessage(ephemeral)));
|
||||
final Optional<Versionstamp> versionstamp = foundationDbMessageStore.insert(aci, messagesByDeviceId).join();
|
||||
assertNotNull(versionstamp);
|
||||
final Map<Byte, FoundationDbMessageStore.InsertResult> result = foundationDbMessageStore.insert(aci, messagesByDeviceId).join();
|
||||
assertNotNull(result);
|
||||
|
||||
final Optional<Versionstamp> returnedVersionstamp = result.values().stream().findFirst()
|
||||
.flatMap(FoundationDbMessageStore.InsertResult::versionstamp);
|
||||
if (expectMessagesInserted) {
|
||||
assertTrue(versionstamp.isPresent());
|
||||
assertTrue(returnedVersionstamp.isPresent());
|
||||
assertTrue(result.values().stream().allMatch(insertResult -> returnedVersionstamp.equals(insertResult.versionstamp())));
|
||||
final Map<Byte, MessageProtos.Envelope> storedMessagesByDeviceId = deviceIds.stream()
|
||||
.collect(Collectors.toMap(Function.identity(), deviceId -> {
|
||||
try {
|
||||
return MessageProtos.Envelope.parseFrom(getMessageByVersionstamp(aci, deviceId, versionstamp.get()));
|
||||
return MessageProtos.Envelope.parseFrom(
|
||||
getMessageByVersionstamp(aci, deviceId, returnedVersionstamp.get()));
|
||||
} catch (final InvalidProtocolBufferException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
@@ -84,28 +95,32 @@ class FoundationDbMessageStoreTest {
|
||||
|
||||
assertEquals(messagesByDeviceId, storedMessagesByDeviceId);
|
||||
} else {
|
||||
assertTrue(versionstamp.isEmpty());
|
||||
assertTrue(result.values().stream().allMatch(insertResult -> insertResult.versionstamp().isEmpty()));
|
||||
}
|
||||
|
||||
if (expectVersionstampUpdated) {
|
||||
assertEquals(versionstamp, getMessagesAvailableWatch(aci),
|
||||
final Optional<Versionstamp> messagesAvailableWatchVersionstamp = getMessagesAvailableWatch(aci);
|
||||
assertTrue(messagesAvailableWatchVersionstamp.isPresent());
|
||||
assertEquals(returnedVersionstamp, messagesAvailableWatchVersionstamp,
|
||||
"messages available versionstamp should be the versionstamp of the last insert transaction");
|
||||
} else {
|
||||
assertTrue(getMessagesAvailableWatch(aci).isEmpty());
|
||||
}
|
||||
|
||||
assertTrue(result.values().stream().allMatch(insertResult -> insertResult.present() == expectPresenceState));
|
||||
}
|
||||
|
||||
private static Stream<Arguments> insert() {
|
||||
return Stream.of(
|
||||
Arguments.argumentSet("Non-ephemeral messages with all devices online",
|
||||
10L, false, true, true),
|
||||
10L, false, true, true, true),
|
||||
Arguments.argumentSet(
|
||||
"Ephemeral messages with presence updated exactly at the second before which the device would be considered offline",
|
||||
300L, true, true, true),
|
||||
300L, true, true, true, true),
|
||||
Arguments.argumentSet("Non-ephemeral messages for with all devices offline",
|
||||
310L, false, true, false),
|
||||
310L, false, true, false, false),
|
||||
Arguments.argumentSet("Ephemeral messages with all devices offline",
|
||||
310L, true, false, false)
|
||||
310L, true, false, false, false)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -113,10 +128,15 @@ class FoundationDbMessageStoreTest {
|
||||
void versionstampCorrectlyUpdatedOnMultipleInserts() {
|
||||
final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID());
|
||||
writePresenceKey(aci, Device.PRIMARY_ID, 1, 10L);
|
||||
foundationDbMessageStore.insert(aci, Map.of(Device.PRIMARY_ID, generateRandomMessage(false))).join();
|
||||
final Optional<Versionstamp> secondMessageVersionstamp = foundationDbMessageStore.insert(aci,
|
||||
foundationDbMessageStore.insert(Map.of(aci, Map.of(Device.PRIMARY_ID, generateRandomMessage(false)))).join();
|
||||
final Map<Byte, FoundationDbMessageStore.InsertResult> secondMessageInsertResult = foundationDbMessageStore.insert(aci,
|
||||
Map.of(Device.PRIMARY_ID, generateRandomMessage(false))).join();
|
||||
assertEquals(secondMessageVersionstamp, getMessagesAvailableWatch(aci));
|
||||
|
||||
final Optional<Versionstamp> messagesAvailableWatchVersionstamp = getMessagesAvailableWatch(aci);
|
||||
assertTrue(messagesAvailableWatchVersionstamp.isPresent());
|
||||
assertEquals(
|
||||
secondMessageInsertResult.get(Device.PRIMARY_ID).versionstamp(),
|
||||
messagesAvailableWatchVersionstamp);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@@ -130,24 +150,29 @@ class FoundationDbMessageStoreTest {
|
||||
writePresenceKey(aci, Device.PRIMARY_ID, 1, 10L);
|
||||
final Map<Byte, MessageProtos.Envelope> messagesByDeviceId = deviceIds.stream()
|
||||
.collect(Collectors.toMap(Function.identity(), _ -> generateRandomMessage(ephemeral)));
|
||||
final Optional<Versionstamp> versionstamp = foundationDbMessageStore.insert(aci, messagesByDeviceId).join();
|
||||
assertNotNull(versionstamp);
|
||||
assertTrue(versionstamp.isPresent(),
|
||||
"versionstamp should be present since at least one message should be inserted");
|
||||
final Map<Byte, FoundationDbMessageStore.InsertResult> result = foundationDbMessageStore.insert(aci, messagesByDeviceId).join();
|
||||
assertNotNull(result);
|
||||
final Optional<Versionstamp> returnedVersionstamp = result.get(Device.PRIMARY_ID).versionstamp();
|
||||
assertTrue(returnedVersionstamp.isPresent(),
|
||||
"versionstamp should be present for online device");
|
||||
|
||||
assertArrayEquals(
|
||||
messagesByDeviceId.get(Device.PRIMARY_ID).toByteArray(),
|
||||
getMessageByVersionstamp(aci, Device.PRIMARY_ID, versionstamp.get()),
|
||||
getMessageByVersionstamp(aci, Device.PRIMARY_ID, returnedVersionstamp.get()),
|
||||
"Message for primary should always be stored since it has a recently updated presence");
|
||||
|
||||
if (ephemeral) {
|
||||
assertTrue(IntStream.range(Device.PRIMARY_ID + 1, Device.PRIMARY_ID + 6)
|
||||
.mapToObj(deviceId -> getMessageByVersionstamp(aci, (byte) deviceId, versionstamp.get()))
|
||||
.mapToObj(deviceId -> getMessageByVersionstamp(aci, (byte) deviceId, returnedVersionstamp.get()))
|
||||
.allMatch(Objects::isNull), "Ephemeral messages for non-present devices must not be stored");
|
||||
assertTrue(IntStream.range(Device.PRIMARY_ID + 1, Device.PRIMARY_ID + 6)
|
||||
.mapToObj(deviceId -> result.get((byte) deviceId).versionstamp())
|
||||
.allMatch(Optional::isEmpty),
|
||||
"Unexpected versionstamp found for one or more devices that didn't have any messages inserted");
|
||||
} else {
|
||||
IntStream.range(Device.PRIMARY_ID + 1, Device.PRIMARY_ID)
|
||||
.forEach(deviceId -> {
|
||||
final byte[] messageBytes = getMessageByVersionstamp(aci, (byte) deviceId, versionstamp.get());
|
||||
final byte[] messageBytes = getMessageByVersionstamp(aci, (byte) deviceId, returnedVersionstamp.get());
|
||||
assertEquals(messagesByDeviceId.get((byte) deviceId).toByteArray(), messageBytes,
|
||||
"Non-ephemeral messages must always be stored");
|
||||
});
|
||||
@@ -169,23 +194,184 @@ class FoundationDbMessageStoreTest {
|
||||
Conversions.longToByteArray(constructPresenceValue(42, getEpochSecondsBeforeClock(5))), true),
|
||||
Arguments.argumentSet("Presence updated same second as current time",
|
||||
Conversions.longToByteArray(constructPresenceValue(42, getEpochSecondsBeforeClock(0))), true),
|
||||
Arguments.argumentSet("Presence updated exactly at the second before which it would have been considered offline",
|
||||
Arguments.argumentSet(
|
||||
"Presence updated exactly at the second before which it would have been considered offline",
|
||||
Conversions.longToByteArray(constructPresenceValue(42, getEpochSecondsBeforeClock(300))), true),
|
||||
Arguments.argumentSet("Presence expired",
|
||||
Conversions.longToByteArray(constructPresenceValue(42, getEpochSecondsBeforeClock(400))), false)
|
||||
);
|
||||
}
|
||||
|
||||
/// Represents a cohort of recipients with the same config
|
||||
record MultiRecipientTestConfig(int shardNum, int numRecipients, boolean devicePresent,
|
||||
boolean generateEphemeralMessages, boolean expectMessagesInserted) {}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void insertMultiRecipient(final List<MultiRecipientTestConfig> testConfigs, final DataSize contentSize,
|
||||
final int[] expectedNumTransactionsByShard) {
|
||||
// Generate a list of ACIs for each test config
|
||||
final List<List<AciServiceIdentifier>> acisByConfig = testConfigs.stream()
|
||||
.map(testConfig -> IntStream.range(0, testConfig.numRecipients())
|
||||
.mapToObj(_ -> generateRandomAciForShard(testConfig.shardNum()))
|
||||
.toList())
|
||||
.toList();
|
||||
|
||||
// Generate MRM bundles for each ACI, for each test config. Later, we'll assert if the stored messages (if expected)
|
||||
// are the same as those we generated.
|
||||
final List<Map<AciServiceIdentifier, Map<Byte, MessageProtos.Envelope>>> mrmByConfig = IntStream.range(0,
|
||||
testConfigs.size())
|
||||
.mapToObj(i -> {
|
||||
final List<AciServiceIdentifier> acis = acisByConfig.get(i);
|
||||
final MultiRecipientTestConfig testConfig = testConfigs.get(i);
|
||||
return acis.stream()
|
||||
.collect(Collectors.toMap(
|
||||
Function.identity(),
|
||||
_ -> Map.of(Device.PRIMARY_ID,
|
||||
generateRandomMessage(testConfig.generateEphemeralMessages(), (int) contentSize.toBytes()))));
|
||||
|
||||
})
|
||||
.toList();
|
||||
|
||||
// Create the consolidated MRM bundle by ACI.
|
||||
final Map<AciServiceIdentifier, Map<Byte, MessageProtos.Envelope>> mrmBundle = new HashMap<>();
|
||||
mrmByConfig.forEach(mrmBundle::putAll);
|
||||
|
||||
// Write a presence key for the cohort of recipients if the config indicates that the device must be present.
|
||||
for (int i = 0; i < testConfigs.size(); i++) {
|
||||
final List<AciServiceIdentifier> acis = acisByConfig.get(i);
|
||||
final MultiRecipientTestConfig testConfig = testConfigs.get(i);
|
||||
if (testConfig.devicePresent()) {
|
||||
acis.forEach(aci -> writePresenceKey(aci, Device.PRIMARY_ID, 1, 10L));
|
||||
}
|
||||
}
|
||||
|
||||
final Map<AciServiceIdentifier, Map<Byte, FoundationDbMessageStore.InsertResult>> result = foundationDbMessageStore.insert(mrmBundle).join();
|
||||
assertNotNull(result);
|
||||
|
||||
// Compute the set of versionstamps by shard number from the individual device insert results, so that we can
|
||||
// assert that each shard has the expected number of committed transactions.
|
||||
final Map<Integer, Set<Versionstamp>> returnedVersionstampsByShard = new HashMap<>();
|
||||
result.forEach((aci, deviceResults) -> {
|
||||
final int shardNum = foundationDbMessageStore.hashAciToShardNumber(aci);
|
||||
final Set<Versionstamp> versionstampSet = returnedVersionstampsByShard.computeIfAbsent(shardNum, _ -> new HashSet<>());
|
||||
deviceResults.forEach((_, deviceResult) -> deviceResult.versionstamp().ifPresent(versionstampSet::add));
|
||||
});
|
||||
|
||||
final int[] returnedNumVersionstampsByShard = new int[FOUNDATION_DB_EXTENSION.getDatabases().length];
|
||||
for (int i = 0; i < returnedNumVersionstampsByShard.length; i++) {
|
||||
returnedNumVersionstampsByShard[i] = returnedVersionstampsByShard.getOrDefault(i, Collections.emptySet()).size();
|
||||
}
|
||||
|
||||
assertArrayEquals(expectedNumTransactionsByShard, returnedNumVersionstampsByShard);
|
||||
|
||||
// For each cohort of recipients, check whether the stored messages (if expected) are the same as those we inserted
|
||||
// and whether the returned device presence states are the same as the configured states.
|
||||
IntStream.range(0, testConfigs.size()).forEach(i -> {
|
||||
final List<AciServiceIdentifier> acis = acisByConfig.get(i);
|
||||
final MultiRecipientTestConfig shardConfig = testConfigs.get(i);
|
||||
if (shardConfig.expectMessagesInserted()) {
|
||||
final Map<AciServiceIdentifier, Map<Byte, MessageProtos.Envelope>> storedMrmBundle = acis.stream()
|
||||
.collect(Collectors.toMap(Function.identity(), aci -> {
|
||||
final List<KeyValue> items = getItemsInDeviceQueue(aci, Device.PRIMARY_ID);
|
||||
assertEquals(1, items.size());
|
||||
try {
|
||||
final MessageProtos.Envelope envelope = MessageProtos.Envelope.parseFrom(items.getFirst().getValue());
|
||||
return Map.of(Device.PRIMARY_ID, envelope);
|
||||
} catch (final InvalidProtocolBufferException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
}));
|
||||
assertEquals(mrmByConfig.get(i), storedMrmBundle,
|
||||
"Stored message bundle does not match inserted message bundle");
|
||||
} else {
|
||||
assertEquals(0, acis
|
||||
.stream()
|
||||
.mapToInt(aci -> getItemsInDeviceQueue(aci, Device.PRIMARY_ID).size())
|
||||
.sum(), "Unexpected messages found in device queue");
|
||||
}
|
||||
|
||||
assertTrue(acis
|
||||
.stream()
|
||||
.allMatch(
|
||||
aci -> result.get(aci).get(Device.PRIMARY_ID).present() == shardConfig.devicePresent()),
|
||||
"Device presence state from insert result does not match expected state");
|
||||
});
|
||||
}
|
||||
|
||||
static Stream<Arguments> insertMultiRecipient() {
|
||||
return Stream.of(
|
||||
Arguments.argumentSet("Multiple recipients on a single shard should result in a single transaction",
|
||||
List.of(
|
||||
new MultiRecipientTestConfig(0, 5, true, false, true)),
|
||||
DataSize.bytes(128), new int[] {1, 0}),
|
||||
Arguments.argumentSet(
|
||||
"Multiple recipients on a single shard exceeding the transaction limit should be broken up into multiple transactions",
|
||||
List.of(
|
||||
new MultiRecipientTestConfig(0, 15, true, false, true)),
|
||||
DataSize.kilobytes(90), new int[] {2, 0}),
|
||||
Arguments.argumentSet("Multiple recipients on different shards should result in multiple transactions",
|
||||
List.of(
|
||||
new MultiRecipientTestConfig(0, 5, true, false, true),
|
||||
new MultiRecipientTestConfig(1, 5, true, false, true)),
|
||||
DataSize.bytes(128), new int[] {1, 1}),
|
||||
Arguments.argumentSet(
|
||||
"Multiple recipients on different shards each exceeding the transaction limit should be broken up into multiple transactions on each shard",
|
||||
List.of(
|
||||
new MultiRecipientTestConfig(0, 15, true, false, true),
|
||||
new MultiRecipientTestConfig(1, 15, true, false, true)),
|
||||
DataSize.kilobytes(90), new int[] {2, 2}),
|
||||
Arguments.argumentSet(
|
||||
"Multiple recipients on a single shard with ephemeral messages and no devices present should result in no transactions committed",
|
||||
List.of(
|
||||
new MultiRecipientTestConfig(0, 5, false, true, false)),
|
||||
DataSize.bytes(128), new int[] {0, 0}),
|
||||
Arguments.argumentSet(
|
||||
"Multiple recipients on different shards with ephemeral messages and no devices present should result in no transactions committed",
|
||||
List.of(
|
||||
new MultiRecipientTestConfig(0, 5, false, true, false),
|
||||
new MultiRecipientTestConfig(1, 5, false, true, false)),
|
||||
DataSize.bytes(128), new int[] {0, 0}),
|
||||
Arguments.argumentSet(
|
||||
"Multiple recipients on two shards with one shard having no devices present should result in only one transaction",
|
||||
List.of(
|
||||
new MultiRecipientTestConfig(0, 5, false, true, false),
|
||||
new MultiRecipientTestConfig(1, 5, true, true, true)),
|
||||
DataSize.bytes(128), new int[] {0, 1}),
|
||||
Arguments.argumentSet(
|
||||
"Multiple recipients on a single shard with some recipients having no devices present should result in only one transaction",
|
||||
List.of(
|
||||
new MultiRecipientTestConfig(0, 3, false, true, false),
|
||||
new MultiRecipientTestConfig(0, 3, true, true, true)),
|
||||
DataSize.bytes(128), new int[] {1, 0}),
|
||||
Arguments.argumentSet(
|
||||
"Multiple recipients on a single shard with total size just exceeding 2 chunks should result in 3 transactions",
|
||||
List.of(
|
||||
new MultiRecipientTestConfig(0, 23, true, false, true)),
|
||||
DataSize.kilobytes(90), new int[] {3, 0})
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void insertEmptyBundle() {
|
||||
assertThrows(IllegalArgumentException.class, () -> foundationDbMessageStore.insert(
|
||||
Map.of(generateRandomAciForShard(0), Collections.emptyMap())));
|
||||
}
|
||||
|
||||
private static MessageProtos.Envelope generateRandomMessage(final boolean ephemeral) {
|
||||
return generateRandomMessage(ephemeral, 16);
|
||||
}
|
||||
|
||||
private static MessageProtos.Envelope generateRandomMessage(final boolean ephemeral, final int contentSize) {
|
||||
return MessageProtos.Envelope.newBuilder()
|
||||
.setContent(ByteString.copyFrom(TestRandomUtil.nextBytes(16)))
|
||||
.setContent(ByteString.copyFrom(TestRandomUtil.nextBytes(contentSize)))
|
||||
.setEphemeral(ephemeral)
|
||||
.build();
|
||||
}
|
||||
|
||||
private byte[] getMessageByVersionstamp(final AciServiceIdentifier aci, final byte deviceId,
|
||||
final Versionstamp versionstamp) {
|
||||
return FOUNDATION_DB_EXTENSION.getDatabase().read(transaction -> {
|
||||
return foundationDbMessageStore.getShardForAci(aci).read(transaction -> {
|
||||
final byte[] key = foundationDbMessageStore.getDeviceQueueSubspace(aci, deviceId)
|
||||
.pack(Tuple.from(versionstamp));
|
||||
return transaction.get(key);
|
||||
@@ -193,7 +379,7 @@ class FoundationDbMessageStoreTest {
|
||||
}
|
||||
|
||||
private Optional<Versionstamp> getMessagesAvailableWatch(final AciServiceIdentifier aci) {
|
||||
return FOUNDATION_DB_EXTENSION.getDatabase()
|
||||
return foundationDbMessageStore.getShardForAci(aci)
|
||||
.read(transaction -> transaction.get(foundationDbMessageStore.getMessagesAvailableWatchKey(aci))
|
||||
.thenApply(value -> value == null ? null : Tuple.fromBytes(value).getVersionstamp(0))
|
||||
.thenApply(Optional::ofNullable))
|
||||
@@ -202,7 +388,7 @@ class FoundationDbMessageStoreTest {
|
||||
|
||||
private void writePresenceKey(final AciServiceIdentifier aci, final byte deviceId, final int serverId,
|
||||
final long secondsBeforeCurrentTime) {
|
||||
FOUNDATION_DB_EXTENSION.getDatabase().run(transaction -> {
|
||||
foundationDbMessageStore.getShardForAci(aci).run(transaction -> {
|
||||
final byte[] presenceKey = foundationDbMessageStore.getPresenceKey(aci, deviceId);
|
||||
final long presenceUpdateEpochSeconds = getEpochSecondsBeforeClock(secondsBeforeCurrentTime);
|
||||
final long presenceValue = constructPresenceValue(serverId, presenceUpdateEpochSeconds);
|
||||
@@ -219,4 +405,19 @@ class FoundationDbMessageStoreTest {
|
||||
return (long) (serverId & 0x0ffff) << 48 | (presenceUpdateEpochSeconds & 0x0000ffffffffffffL);
|
||||
}
|
||||
|
||||
private AciServiceIdentifier generateRandomAciForShard(final int shardNumber) {
|
||||
assert shardNumber < FOUNDATION_DB_EXTENSION.getDatabases().length;
|
||||
while (true) {
|
||||
final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID());
|
||||
if (foundationDbMessageStore.hashAciToShardNumber(aci) == shardNumber) {
|
||||
return aci;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private List<KeyValue> getItemsInDeviceQueue(final AciServiceIdentifier aci, final byte deviceId) {
|
||||
return foundationDbMessageStore.getShardForAci(aci).readAsync(transaction -> AsyncUtil.collect(transaction.getRange(
|
||||
foundationDbMessageStore.getDeviceQueueSubspace(aci, deviceId).range()))).join();
|
||||
}
|
||||
|
||||
}
|
||||
+31
-36
@@ -6,6 +6,8 @@
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatException;
|
||||
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.reset;
|
||||
@@ -26,21 +28,17 @@ import com.apple.itunes.storekit.model.SubscriptionGroupIdentifierItem;
|
||||
import com.apple.itunes.storekit.verification.SignedDataVerifier;
|
||||
import com.apple.itunes.storekit.verification.VerificationException;
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.math.BigDecimal;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.EnumSource;
|
||||
import org.whispersystems.textsecuregcm.storage.SubscriptionException;
|
||||
import org.whispersystems.textsecuregcm.util.CompletableFutureTestUtil;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
|
||||
class AppleAppStoreManagerTest {
|
||||
|
||||
@@ -54,27 +52,19 @@ class AppleAppStoreManagerTest {
|
||||
|
||||
private final AppStoreServerAPIClient apiClient = mock(AppStoreServerAPIClient.class);
|
||||
private final SignedDataVerifier signedDataVerifier = mock(SignedDataVerifier.class);
|
||||
private ScheduledExecutorService executor;
|
||||
private AppleAppStoreManager appleAppStoreManager;
|
||||
|
||||
@BeforeEach
|
||||
public void setup() {
|
||||
reset(apiClient, signedDataVerifier);
|
||||
executor = Executors.newSingleThreadScheduledExecutor();
|
||||
appleAppStoreManager = new AppleAppStoreManager(apiClient, signedDataVerifier,
|
||||
SUBSCRIPTION_GROUP_ID, Map.of(PRODUCT_ID, LEVEL), null, executor, executor);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
public void teardown() throws InterruptedException {
|
||||
executor.shutdownNow();
|
||||
executor.awaitTermination(1, TimeUnit.SECONDS);
|
||||
SUBSCRIPTION_GROUP_ID, Map.of(PRODUCT_ID, LEVEL), null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void lookupTransaction() throws APIException, IOException, VerificationException {
|
||||
public void lookupTransaction() throws APIException, IOException, VerificationException, SubscriptionException, RateLimitExceededException {
|
||||
mockValidSubscription();
|
||||
final SubscriptionInformation info = appleAppStoreManager.getSubscriptionInformation(ORIGINAL_TX_ID).join();
|
||||
final SubscriptionInformation info = appleAppStoreManager.getSubscriptionInformation(ORIGINAL_TX_ID);
|
||||
|
||||
assertThat(info.active()).isTrue();
|
||||
assertThat(info.paymentProcessing()).isFalse();
|
||||
@@ -85,15 +75,17 @@ class AppleAppStoreManagerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void validateTransaction() throws VerificationException, APIException, IOException {
|
||||
public void validateTransaction()
|
||||
throws VerificationException, APIException, IOException, SubscriptionException, RateLimitExceededException {
|
||||
mockValidSubscription();
|
||||
assertThat(appleAppStoreManager.validateTransaction(ORIGINAL_TX_ID).join()).isEqualTo(LEVEL);
|
||||
assertThat(appleAppStoreManager.validateTransaction(ORIGINAL_TX_ID)).isEqualTo(LEVEL);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void generateReceipt() throws VerificationException, APIException, IOException {
|
||||
public void generateReceipt()
|
||||
throws VerificationException, APIException, IOException, SubscriptionException, RateLimitExceededException {
|
||||
mockValidSubscription();
|
||||
final SubscriptionPaymentProcessor.ReceiptItem receipt = appleAppStoreManager.getReceiptItem(ORIGINAL_TX_ID).join();
|
||||
final SubscriptionPaymentProcessor.ReceiptItem receipt = appleAppStoreManager.getReceiptItem(ORIGINAL_TX_ID);
|
||||
assertThat(receipt.level()).isEqualTo(LEVEL);
|
||||
assertThat(receipt.paymentTime().receiptExpiration(Duration.ofDays(1), Duration.ZERO))
|
||||
.isEqualTo(Instant.EPOCH.plus(Duration.ofDays(2)));
|
||||
@@ -101,16 +93,17 @@ class AppleAppStoreManagerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void generateReceiptExpired() throws VerificationException, APIException, IOException {
|
||||
public void generateReceiptExpired()
|
||||
throws VerificationException, APIException, IOException {
|
||||
mockSubscription(Status.EXPIRED, AutoRenewStatus.ON);
|
||||
CompletableFutureTestUtil.assertFailsWithCause(SubscriptionException.PaymentRequired.class,
|
||||
appleAppStoreManager.getReceiptItem(ORIGINAL_TX_ID));
|
||||
assertThatExceptionOfType(SubscriptionPaymentRequiredException.class)
|
||||
.isThrownBy(() -> appleAppStoreManager.getReceiptItem(ORIGINAL_TX_ID));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void autoRenewOff() throws VerificationException, APIException, IOException {
|
||||
public void autoRenewOff() throws VerificationException, APIException, IOException, SubscriptionException, RateLimitExceededException {
|
||||
mockSubscription(Status.ACTIVE, AutoRenewStatus.OFF);
|
||||
final SubscriptionInformation info = appleAppStoreManager.getSubscriptionInformation(ORIGINAL_TX_ID).join();
|
||||
final SubscriptionInformation info = appleAppStoreManager.getSubscriptionInformation(ORIGINAL_TX_ID);
|
||||
|
||||
assertThat(info.cancelAtPeriodEnd()).isTrue();
|
||||
|
||||
@@ -121,7 +114,7 @@ class AppleAppStoreManagerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void lookupMultipleProducts() throws APIException, IOException, VerificationException {
|
||||
public void lookupMultipleProducts() throws APIException, IOException, VerificationException, RateLimitExceededException, SubscriptionException {
|
||||
// The lookup should select the transaction at i=1
|
||||
final List<String> products = List.of("otherProduct1", PRODUCT_ID, "otherProduct3");
|
||||
|
||||
@@ -149,14 +142,14 @@ class AppleAppStoreManagerTest {
|
||||
.originalPurchaseDate(Instant.EPOCH.toEpochMilli())
|
||||
.expiresDate(Instant.EPOCH.plus(Duration.ofDays(1)).toEpochMilli()));
|
||||
}
|
||||
final SubscriptionInformation info = appleAppStoreManager.getSubscriptionInformation(ORIGINAL_TX_ID).join();
|
||||
final SubscriptionInformation info = appleAppStoreManager.getSubscriptionInformation(ORIGINAL_TX_ID);
|
||||
|
||||
assertThat(info.price().amount().compareTo(new BigDecimal("100"))).isEqualTo(0);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void retryEventuallyWorks() throws APIException, IOException, VerificationException {
|
||||
public void retryEventuallyWorks() throws APIException, IOException, VerificationException, RateLimitExceededException, SubscriptionException {
|
||||
// Should retry up to 3 times
|
||||
when(apiClient.getAllSubscriptionStatuses(ORIGINAL_TX_ID, new Status[]{}))
|
||||
.thenThrow(new APIException(404, APIError.ORIGINAL_TRANSACTION_ID_NOT_FOUND_RETRYABLE.errorCode(), "test"))
|
||||
@@ -169,7 +162,7 @@ class AppleAppStoreManagerTest {
|
||||
.signedRenewalInfo(SIGNED_RENEWAL_INFO)
|
||||
.signedTransactionInfo(SIGNED_TX_INFO)))));
|
||||
mockDecode(AutoRenewStatus.ON);
|
||||
final SubscriptionInformation info = appleAppStoreManager.getSubscriptionInformation(ORIGINAL_TX_ID).join();
|
||||
final SubscriptionInformation info = appleAppStoreManager.getSubscriptionInformation(ORIGINAL_TX_ID);
|
||||
assertThat(info.status()).isEqualTo(SubscriptionStatus.ACTIVE);
|
||||
}
|
||||
|
||||
@@ -179,8 +172,10 @@ class AppleAppStoreManagerTest {
|
||||
when(apiClient.getAllSubscriptionStatuses(ORIGINAL_TX_ID, new Status[]{}))
|
||||
.thenThrow(new APIException(404, APIError.ORIGINAL_TRANSACTION_ID_NOT_FOUND_RETRYABLE.errorCode(), "test"));
|
||||
mockDecode(AutoRenewStatus.ON);
|
||||
CompletableFutureTestUtil.assertFailsWithCause(APIException.class,
|
||||
appleAppStoreManager.getSubscriptionInformation(ORIGINAL_TX_ID));
|
||||
assertThatException()
|
||||
.isThrownBy(() -> appleAppStoreManager.getSubscriptionInformation(ORIGINAL_TX_ID))
|
||||
.isInstanceOf(UncheckedIOException.class)
|
||||
.withRootCauseInstanceOf(APIException.class);
|
||||
|
||||
verify(apiClient, times(3)).getAllSubscriptionStatuses(ORIGINAL_TX_ID, new Status[]{});
|
||||
|
||||
@@ -189,22 +184,22 @@ class AppleAppStoreManagerTest {
|
||||
@Test
|
||||
public void cancelRenewalDisabled() throws APIException, VerificationException, IOException {
|
||||
mockSubscription(Status.ACTIVE, AutoRenewStatus.OFF);
|
||||
assertDoesNotThrow(() -> appleAppStoreManager.cancelAllActiveSubscriptions(ORIGINAL_TX_ID).join());
|
||||
assertDoesNotThrow(() -> appleAppStoreManager.cancelAllActiveSubscriptions(ORIGINAL_TX_ID));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@EnumSource(mode = EnumSource.Mode.EXCLUDE, names = {"EXPIRED", "REVOKED"})
|
||||
public void cancelFailsForActiveSubscription(Status status) throws APIException, VerificationException, IOException {
|
||||
mockSubscription(status, AutoRenewStatus.ON);
|
||||
CompletableFutureTestUtil.assertFailsWithCause(SubscriptionException.InvalidArguments.class,
|
||||
appleAppStoreManager.cancelAllActiveSubscriptions(ORIGINAL_TX_ID));
|
||||
assertThatExceptionOfType(SubscriptionInvalidArgumentsException.class)
|
||||
.isThrownBy(() -> appleAppStoreManager.cancelAllActiveSubscriptions(ORIGINAL_TX_ID));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@EnumSource(mode = EnumSource.Mode.INCLUDE, names = {"EXPIRED", "REVOKED"})
|
||||
public void cancelInactiveStatus(Status status) throws APIException, VerificationException, IOException {
|
||||
mockSubscription(status, AutoRenewStatus.ON);
|
||||
assertDoesNotThrow(() -> appleAppStoreManager.cancelAllActiveSubscriptions(ORIGINAL_TX_ID).join());
|
||||
assertDoesNotThrow(() -> appleAppStoreManager.cancelAllActiveSubscriptions(ORIGINAL_TX_ID));
|
||||
}
|
||||
|
||||
private void mockSubscription(final Status status, final AutoRenewStatus autoRenewStatus)
|
||||
|
||||
+1
-1
@@ -51,6 +51,6 @@ class BraintreeManagerTest {
|
||||
when(braintreeGateway.customer()).thenReturn(customerGateway);
|
||||
|
||||
assertTimeoutPreemptively(Duration.ofSeconds(5), () ->
|
||||
braintreeManager.cancelAllActiveSubscriptions("customerId")).join();
|
||||
braintreeManager.cancelAllActiveSubscriptions("customerId"));
|
||||
}
|
||||
}
|
||||
+39
-47
@@ -5,6 +5,8 @@
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatException;
|
||||
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
|
||||
import static org.assertj.core.api.Assertions.assertThatNoException;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
@@ -31,12 +33,7 @@ import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.stream.Stream;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
@@ -44,8 +41,6 @@ import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.EnumSource;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.storage.SubscriptionException;
|
||||
import org.whispersystems.textsecuregcm.util.CompletableFutureTestUtil;
|
||||
import org.whispersystems.textsecuregcm.util.MockUtils;
|
||||
import org.whispersystems.textsecuregcm.util.MutableClock;
|
||||
|
||||
@@ -74,7 +69,6 @@ class GooglePlayBillingManagerTest {
|
||||
|
||||
private final MutableClock clock = MockUtils.mutableClock(0L);
|
||||
|
||||
private ExecutorService executor;
|
||||
private GooglePlayBillingManager googlePlayBillingManager;
|
||||
|
||||
@BeforeEach
|
||||
@@ -105,19 +99,12 @@ class GooglePlayBillingManagerTest {
|
||||
when(monetization.subscriptions()).thenReturn(msubscriptions);
|
||||
when(msubscriptions.get(PACKAGE_NAME, PRODUCT_ID)).thenReturn(subscriptionConfig);
|
||||
|
||||
executor = Executors.newSingleThreadExecutor();
|
||||
googlePlayBillingManager = new GooglePlayBillingManager(
|
||||
androidPublisher, clock, PACKAGE_NAME, Map.of(PRODUCT_ID, 201L), executor);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
public void teardown() throws InterruptedException {
|
||||
executor.shutdownNow();
|
||||
executor.awaitTermination(1, TimeUnit.SECONDS);
|
||||
androidPublisher, clock, PACKAGE_NAME, Map.of(PRODUCT_ID, 201L));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void validatePurchase() throws IOException {
|
||||
public void validatePurchase() throws IOException, RateLimitExceededException, SubscriptionException {
|
||||
when(subscriptionsv2Get.execute()).thenReturn(new SubscriptionPurchaseV2()
|
||||
.setAcknowledgementState(GooglePlayBillingManager.AcknowledgementState.PENDING.apiString())
|
||||
.setSubscriptionState(GooglePlayBillingManager.SubscriptionState.ACTIVE.apiString())
|
||||
@@ -125,11 +112,10 @@ class GooglePlayBillingManagerTest {
|
||||
.setExpiryTime(Instant.now().plus(Duration.ofDays(1)).toString())
|
||||
.setProductId(PRODUCT_ID))));
|
||||
|
||||
final GooglePlayBillingManager.ValidatedToken result = googlePlayBillingManager
|
||||
.validateToken(PURCHASE_TOKEN).join();
|
||||
final GooglePlayBillingManager.ValidatedToken result = googlePlayBillingManager.validateToken(PURCHASE_TOKEN);
|
||||
|
||||
assertThat(result.getLevel()).isEqualTo(201);
|
||||
assertThatNoException().isThrownBy(() -> result.acknowledgePurchase().join());
|
||||
assertThatNoException().isThrownBy(result::acknowledgePurchase);
|
||||
verify(acknowledge, times(1)).execute();
|
||||
}
|
||||
|
||||
@@ -143,16 +129,16 @@ class GooglePlayBillingManagerTest {
|
||||
.setExpiryTime(Instant.now().plus(Duration.ofDays(1)).toString())
|
||||
.setProductId(PRODUCT_ID))));
|
||||
|
||||
final CompletableFuture<GooglePlayBillingManager.ValidatedToken> future = googlePlayBillingManager
|
||||
.validateToken(PURCHASE_TOKEN);
|
||||
switch (subscriptionState) {
|
||||
case ACTIVE, IN_GRACE_PERIOD, CANCELED -> assertThatNoException().isThrownBy(() -> future.join());
|
||||
default -> CompletableFutureTestUtil.assertFailsWithCause(SubscriptionException.PaymentRequired.class, future);
|
||||
case ACTIVE, IN_GRACE_PERIOD, CANCELED -> assertThatNoException()
|
||||
.isThrownBy(() -> googlePlayBillingManager.validateToken(PURCHASE_TOKEN));
|
||||
default -> assertThatExceptionOfType(SubscriptionPaymentRequiredException.class)
|
||||
.isThrownBy(() -> googlePlayBillingManager.validateToken(PURCHASE_TOKEN));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void avoidDoubleAcknowledge() throws IOException {
|
||||
public void avoidDoubleAcknowledge() throws IOException, RateLimitExceededException, SubscriptionException {
|
||||
when(subscriptionsv2Get.execute()).thenReturn(new SubscriptionPurchaseV2()
|
||||
.setAcknowledgementState(GooglePlayBillingManager.AcknowledgementState.ACKNOWLEDGED.apiString())
|
||||
.setSubscriptionState(GooglePlayBillingManager.SubscriptionState.ACTIVE.apiString())
|
||||
@@ -160,11 +146,10 @@ class GooglePlayBillingManagerTest {
|
||||
.setExpiryTime(Instant.now().plus(Duration.ofDays(1)).toString())
|
||||
.setProductId(PRODUCT_ID))));
|
||||
|
||||
final GooglePlayBillingManager.ValidatedToken result = googlePlayBillingManager
|
||||
.validateToken(PURCHASE_TOKEN).join();
|
||||
final GooglePlayBillingManager.ValidatedToken result = googlePlayBillingManager.validateToken(PURCHASE_TOKEN);
|
||||
|
||||
assertThat(result.getLevel()).isEqualTo(201);
|
||||
assertThatNoException().isThrownBy(() -> result.acknowledgePurchase().join());
|
||||
assertThatNoException().isThrownBy(result::acknowledgePurchase);
|
||||
verifyNoInteractions(acknowledge);
|
||||
}
|
||||
|
||||
@@ -178,7 +163,7 @@ class GooglePlayBillingManagerTest {
|
||||
.setExpiryTime(Instant.now().plus(Duration.ofDays(1)).toString())
|
||||
.setProductId(PRODUCT_ID))));
|
||||
assertThatNoException().isThrownBy(() ->
|
||||
googlePlayBillingManager.cancelAllActiveSubscriptions(PURCHASE_TOKEN).join());
|
||||
googlePlayBillingManager.cancelAllActiveSubscriptions(PURCHASE_TOKEN));
|
||||
final int wanted = switch (subscriptionState) {
|
||||
case CANCELED, EXPIRED -> 0;
|
||||
default -> 1;
|
||||
@@ -192,7 +177,7 @@ class GooglePlayBillingManagerTest {
|
||||
when(mockException.getStatusCode()).thenReturn(404);
|
||||
when(subscriptionsv2Get.execute()).thenThrow(mockException);
|
||||
assertThatNoException().isThrownBy(() ->
|
||||
googlePlayBillingManager.cancelAllActiveSubscriptions(PURCHASE_TOKEN).join());
|
||||
googlePlayBillingManager.cancelAllActiveSubscriptions(PURCHASE_TOKEN));
|
||||
verifyNoInteractions(cancel);
|
||||
}
|
||||
|
||||
@@ -201,8 +186,8 @@ class GooglePlayBillingManagerTest {
|
||||
final HttpResponseException mockException = mock(HttpResponseException.class);
|
||||
when(mockException.getStatusCode()).thenReturn(429);
|
||||
when(subscriptionsv2Get.execute()).thenThrow(mockException);
|
||||
CompletableFutureTestUtil.assertFailsWithCause(
|
||||
RateLimitExceededException.class, googlePlayBillingManager.getSubscriptionInformation(PURCHASE_TOKEN));
|
||||
assertThatExceptionOfType(RateLimitExceededException.class).isThrownBy(() ->
|
||||
googlePlayBillingManager.getSubscriptionInformation(PURCHASE_TOKEN));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -213,13 +198,13 @@ class GooglePlayBillingManagerTest {
|
||||
.setLineItems(List.of(new SubscriptionPurchaseLineItem()
|
||||
.setExpiryTime(Instant.now().plus(Duration.ofDays(1)).toString())
|
||||
.setProductId(PRODUCT_ID))));
|
||||
CompletableFutureTestUtil.assertFailsWithCause(
|
||||
IllegalStateException.class,
|
||||
assertThatExceptionOfType(IllegalStateException.class).isThrownBy(() ->
|
||||
googlePlayBillingManager.getReceiptItem(PURCHASE_TOKEN));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getReceiptExpiring() throws IOException {
|
||||
public void getReceiptExpiring()
|
||||
throws IOException, RateLimitExceededException, SubscriptionException {
|
||||
final Instant day9 = Instant.EPOCH.plus(Duration.ofDays(9));
|
||||
final Instant day10 = Instant.EPOCH.plus(Duration.ofDays(10));
|
||||
|
||||
@@ -232,7 +217,7 @@ class GooglePlayBillingManagerTest {
|
||||
.setProductId(PRODUCT_ID))));
|
||||
|
||||
clock.setTimeInstant(day9);
|
||||
SubscriptionPaymentProcessor.ReceiptItem item = googlePlayBillingManager.getReceiptItem(PURCHASE_TOKEN).join();
|
||||
SubscriptionPaymentProcessor.ReceiptItem item = googlePlayBillingManager.getReceiptItem(PURCHASE_TOKEN);
|
||||
assertThat(item.itemId()).isEqualTo(ORDER_ID);
|
||||
assertThat(item.level()).isEqualTo(201L);
|
||||
|
||||
@@ -242,19 +227,18 @@ class GooglePlayBillingManagerTest {
|
||||
|
||||
// should still be able to get a receipt the next day
|
||||
clock.setTimeInstant(day10);
|
||||
item = googlePlayBillingManager.getReceiptItem(PURCHASE_TOKEN).join();
|
||||
item = googlePlayBillingManager.getReceiptItem(PURCHASE_TOKEN);
|
||||
assertThat(item.itemId()).isEqualTo(ORDER_ID);
|
||||
|
||||
// next second should be expired
|
||||
clock.setTimeInstant(day10.plus(Duration.ofSeconds(1)));
|
||||
|
||||
CompletableFutureTestUtil.assertFailsWithCause(
|
||||
SubscriptionException.PaymentRequired.class,
|
||||
googlePlayBillingManager.getReceiptItem(PURCHASE_TOKEN));
|
||||
assertThatExceptionOfType(SubscriptionPaymentRequiredException.class)
|
||||
.isThrownBy(() -> googlePlayBillingManager.getReceiptItem(PURCHASE_TOKEN));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getSubscriptionInfo() throws IOException {
|
||||
public void getSubscriptionInfo() throws IOException, RateLimitExceededException, SubscriptionException {
|
||||
final String basePlanId = "basePlanId";
|
||||
when(subscriptionsv2Get.execute()).thenReturn(new SubscriptionPurchaseV2()
|
||||
.setAcknowledgementState(GooglePlayBillingManager.AcknowledgementState.ACKNOWLEDGED.apiString())
|
||||
@@ -275,7 +259,7 @@ class GooglePlayBillingManagerTest {
|
||||
.setPrice(new Money().setCurrencyCode("USD").setUnits(1L).setNanos(750_000_000))));
|
||||
when(subscriptionConfig.execute()).thenReturn(new Subscription().setBasePlans(List.of(basePlan)));
|
||||
|
||||
final SubscriptionInformation info = googlePlayBillingManager.getSubscriptionInformation(PURCHASE_TOKEN).join();
|
||||
final SubscriptionInformation info = googlePlayBillingManager.getSubscriptionInformation(PURCHASE_TOKEN);
|
||||
assertThat(info.active()).isTrue();
|
||||
assertThat(info.paymentProcessing()).isFalse();
|
||||
assertThat(info.price().currency()).isEqualTo("USD");
|
||||
@@ -287,8 +271,8 @@ class GooglePlayBillingManagerTest {
|
||||
|
||||
public static Stream<Arguments> tokenErrors() {
|
||||
return Stream.of(
|
||||
Arguments.of(404, SubscriptionException.NotFound.class),
|
||||
Arguments.of(410, SubscriptionException.NotFound.class),
|
||||
Arguments.of(404, SubscriptionNotFoundException.class),
|
||||
Arguments.of(410, SubscriptionNotFoundException.class),
|
||||
Arguments.of(400, HttpResponseException.class)
|
||||
);
|
||||
}
|
||||
@@ -298,9 +282,17 @@ class GooglePlayBillingManagerTest {
|
||||
final HttpResponseException mockException = mock(HttpResponseException.class);
|
||||
when(mockException.getStatusCode()).thenReturn(httpStatus);
|
||||
when(subscriptionsv2Get.execute()).thenThrow(mockException);
|
||||
|
||||
CompletableFutureTestUtil.assertFailsWithCause(expected,
|
||||
googlePlayBillingManager.getSubscriptionInformation(PURCHASE_TOKEN));
|
||||
assertThatException()
|
||||
.isThrownBy(() -> googlePlayBillingManager.getSubscriptionInformation(PURCHASE_TOKEN))
|
||||
// Verify the exception or its leaf cause is an instanceof expected. withRootCauseInstanceOf almost does what we
|
||||
// want, but fails if the outermost exception does not have a cause
|
||||
.matches(e -> {
|
||||
Throwable cause = e;
|
||||
while (cause.getCause() != null) {
|
||||
cause = cause.getCause();
|
||||
}
|
||||
return expected.isInstance(cause);
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
|
||||
import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.stripe.StripeClient;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import com.stripe.exception.ApiException;
|
||||
import com.stripe.exception.StripeException;
|
||||
import com.stripe.service.SubscriptionService;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class StripeManagerTest {
|
||||
|
||||
private StripeClient stripeClient;
|
||||
private StripeManager stripeManager;
|
||||
private ExecutorService executor;
|
||||
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
this.executor = Executors.newSingleThreadExecutor();
|
||||
this.stripeClient = mock(StripeClient.class);
|
||||
this.stripeManager = new StripeManager(
|
||||
this.stripeClient,
|
||||
executor,
|
||||
"idempotencyKey".getBytes(StandardCharsets.UTF_8),
|
||||
"boost",
|
||||
Map.of(PaymentMethod.CARD, Set.of("usd")));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void teardown() throws InterruptedException {
|
||||
this.executor.shutdownNow();
|
||||
this.executor.awaitTermination(1, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@Test
|
||||
void paymentRequiresAction() throws StripeException {
|
||||
final SubscriptionService subscriptionService = mock(SubscriptionService.class);
|
||||
final ApiException stripeException = new ApiException("Payment intent requires action",
|
||||
UUID.randomUUID().toString(), "subscription_payment_intent_requires_action", 400, new Exception());
|
||||
|
||||
when(subscriptionService.create(any(), any())).thenThrow(stripeException);
|
||||
when(stripeClient.subscriptions()).thenReturn(subscriptionService);
|
||||
assertThatExceptionOfType(SubscriptionPaymentRequiresActionException.class).isThrownBy(() ->
|
||||
stripeManager.createSubscription("customerId", "priceId", 1, 0));
|
||||
}
|
||||
}
|
||||
+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));
|
||||
|
||||
}
|
||||
}
|
||||
Loaded 100 of 109 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user