mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-12-01 05:06:47 +00:00
Compare commits
82
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cdd461b8f4 | ||
|
|
d9a54a0d42 | ||
|
|
3f3aa89b0f | ||
|
|
55fa60dd4e | ||
|
|
b539df8e48 | ||
|
|
0cd0716eb5 | ||
|
|
6386aada73 | ||
|
|
5c44398bb5 | ||
|
|
54736bb117 | ||
|
|
aed8e60789 | ||
|
|
5fa50e8ad7 | ||
|
|
fdaba751bd | ||
|
|
0eebb58956 | ||
|
|
6bb85d77a7 | ||
|
|
9e3844ee5a | ||
|
|
7ee8e349e2 | ||
|
|
4d9e252697 | ||
|
|
222e5a033b | ||
|
|
8c6fbbfa65 | ||
|
|
b0b2122d8c | ||
|
|
d7711e235b | ||
|
|
5174550ef3 | ||
|
|
d0fcb9ab54 | ||
|
|
375150a8c3 | ||
|
|
cb28614721 | ||
|
|
f02caf78cd | ||
|
|
8fd72549fb | ||
|
|
1e4774820f | ||
|
|
48cdad7e57 | ||
|
|
392bab5b60 | ||
|
|
6b67604fe7 | ||
|
|
67a03f81b9 | ||
|
|
90b75cbf22 | ||
|
|
4dede4acad | ||
|
|
d225ba3618 | ||
|
|
8790514b8a | ||
|
|
fa4d3c7ca9 | ||
|
|
1f0b2ad92d | ||
|
|
feb00c6ba6 | ||
|
|
f588390bdb | ||
|
|
355b320c92 | ||
|
|
40fb9c4cee | ||
|
|
aa5ac70ad3 | ||
|
|
2abf55e395 | ||
|
|
808bb16103 | ||
|
|
4743abcfbd | ||
|
|
1b09529ece | ||
|
|
0c3c390a0b | ||
|
|
ca4ee141d8 | ||
|
|
671a6e1d7c | ||
|
|
f4e16676c9 | ||
|
|
78b3147491 | ||
|
|
8b617b64f8 | ||
|
|
28aefe0ebe | ||
|
|
4e52317e26 | ||
|
|
99465c1f41 | ||
|
|
041c29bfa8 | ||
|
|
8e5ad7f52e | ||
|
|
ca5d203f1c | ||
|
|
9a9b15ee0a | ||
|
|
503941ec6a | ||
|
|
ac720595e6 | ||
|
|
8deb5a803a | ||
|
|
45f96cd702 | ||
|
|
4a3275ad63 | ||
|
|
911feceacb | ||
|
|
fe0956c8f7 | ||
|
|
60002a8a0f | ||
|
|
1876b71d39 | ||
|
|
3cfe8b9f6c | ||
|
|
691a4162e1 | ||
|
|
9505e7b1a1 | ||
|
|
569f4f31e8 | ||
|
|
06519ce9d1 | ||
|
|
024fa9ce5f | ||
|
|
7c9e3d029b | ||
|
|
cc6ef53f91 | ||
|
|
4c0f454209 | ||
|
|
9c393972e9 | ||
|
|
31c1bb8940 | ||
|
|
c3b2b43813 | ||
|
|
19f2574799 |
No files matched your search
@@ -11,8 +11,8 @@ jobs:
|
||||
contents: write
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
|
||||
- uses: actions/setup-java@be666c2fcd27ec809703dec50e508c2fdc7f6654 # v5.2.0
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
- uses: actions/setup-java@1bcf9fb12cf4aa7d266a90ae39939e61372fe520 # v5.4.0
|
||||
with:
|
||||
distribution: 'temurin'
|
||||
java-version-file: .java-version
|
||||
|
||||
@@ -17,14 +17,15 @@ jobs:
|
||||
permissions:
|
||||
id-token: write
|
||||
contents: read
|
||||
issues: write
|
||||
steps:
|
||||
- uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
|
||||
- uses: actions/setup-java@be666c2fcd27ec809703dec50e508c2fdc7f6654 # v5.2.0
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
- uses: actions/setup-java@1bcf9fb12cf4aa7d266a90ae39939e61372fe520 # v5.4.0
|
||||
with:
|
||||
distribution: 'temurin'
|
||||
java-version-file: .java-version
|
||||
cache: 'maven'
|
||||
- uses: aws-actions/configure-aws-credentials@e7f100cf4c008499ea8adda475de1042d6975c7b # v6.2.0
|
||||
- uses: aws-actions/configure-aws-credentials@254c19bd240aabef8777f48595e9d2d7b972184b # v6.2.1
|
||||
name: Configure AWS credentials from Test account
|
||||
with:
|
||||
role-to-assume: ${{ vars.AWS_ROLE }}
|
||||
@@ -35,3 +36,11 @@ jobs:
|
||||
echo "${INTEGRATION_TEST_CONFIG}" > integration-tests/src/main/resources/config.yml
|
||||
- name: Run and verify integration tests
|
||||
run: ./mvnw clean compile test-compile failsafe:integration-test failsafe:verify -P aws-sso
|
||||
- name: Open an issue on failure
|
||||
if: ${{ failure() && github.event_name == 'schedule' }}
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
gh issue create \
|
||||
--title "Failed server integration tests ($(date +'%Y-%m-%d'))" \
|
||||
--body "Workflow **${{ github.workflow }}** failed. See the run: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}"
|
||||
@@ -14,20 +14,20 @@ jobs:
|
||||
|
||||
services:
|
||||
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
|
||||
# Note: this should generally match the version of the FoundationDB SERVER deployed in production; no need to
|
||||
# bump it purely to match the CLIENT version
|
||||
image: foundationdb/foundationdb:7.3.68
|
||||
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
|
||||
# Note: this should generally match the version of the FoundationDB SERVER deployed in production; no need to
|
||||
# bump it purely to match the CLIENT version
|
||||
image: foundationdb/foundationdb:7.3.68
|
||||
options: --name foundationdb1
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
- name: Set up JDK
|
||||
uses: actions/setup-java@be666c2fcd27ec809703dec50e508c2fdc7f6654 # v5.2.0
|
||||
uses: actions/setup-java@1bcf9fb12cf4aa7d266a90ae39939e61372fe520 # v5.4.0
|
||||
with:
|
||||
distribution: 'temurin'
|
||||
java-version-file: .java-version
|
||||
@@ -61,7 +61,7 @@ jobs:
|
||||
- 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
|
||||
cp service/target/jib-extra/usr/lib/libfdb_c.so /usr/lib/libfdb_c.x86_64.so
|
||||
ldconfig
|
||||
- name: Build with Maven
|
||||
run: ./mvnw -e -B clean verify -DfoundationDb.serviceContainerNamePrefix=foundationdb
|
||||
@@ -62,7 +62,7 @@ public class WebsocketClientSession implements Session.Listener.AutoDemanding {
|
||||
log.info("received response message {}", response.getStatus());
|
||||
final CompletableFuture<WebSocketResponseMessage> future = responseFutures.remove(response.getRequestId());
|
||||
if (future == null) {
|
||||
throw new IllegalArgumentException("Received response with no matching request: {}" + response.getRequestId());
|
||||
throw new IllegalArgumentException("Received response with no matching request: " + response.getRequestId());
|
||||
}
|
||||
future.complete(response);
|
||||
}
|
||||
|
||||
@@ -50,13 +50,12 @@
|
||||
<commons-csv.version>1.14.1</commons-csv.version>
|
||||
<commons-io.version>2.21.0</commons-io.version>
|
||||
<dropwizard.version>5.0.1</dropwizard.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
|
||||
with even-numbered patch versions). Also when updating FoundationDB, make sure to update the version of FoundationDB
|
||||
used by GitHub Actions. -->
|
||||
<foundationdb.version>7.3.62</foundationdb.version>
|
||||
<!-- Note: We use x86_64 builds without AVX instructions enabled (i.e. FoundationDB versions with even-numbered
|
||||
patch versions). Also when updating FoundationDB, make sure to update the version of FoundationDBused by GitHub
|
||||
Actions. -->
|
||||
<foundationdb.version>7.3.68</foundationdb.version>
|
||||
<foundationdb.api-version>730</foundationdb.api-version>
|
||||
<foundationdb.client-library-sha256>bfed237b787fae3cde1222676e6bfbb0d218fc27bf9e903397a7a7aa96fb2d33</foundationdb.client-library-sha256>
|
||||
<foundationdb.client-library-sha256>8c96a1f7ab561cd38e16e4c269c5e50ae0fd8063854e0d72c89339a7ac1b6873</foundationdb.client-library-sha256>
|
||||
<google-cloud-libraries.version>26.79.0</google-cloud-libraries.version>
|
||||
<grpc.version>1.76.3</grpc.version> <!-- should be kept in sync with the value from Google libraries-bom -->
|
||||
<gson.version>2.13.2</gson.version>
|
||||
@@ -68,7 +67,7 @@
|
||||
<junit-pioneer.version>2.3.0</junit-pioneer.version>
|
||||
<jsr305.version>3.0.2</jsr305.version>
|
||||
<kotlin.version>2.3.20</kotlin.version>
|
||||
<logback.version>1.5.32</logback.version>
|
||||
<logback.version>1.5.38</logback.version>
|
||||
<logback-access-common.version>2.0.12</logback-access-common.version>
|
||||
<lettuce.version>7.5.1.RELEASE</lettuce.version>
|
||||
<libphonenumber.version>9.0.21</libphonenumber.version>
|
||||
@@ -287,7 +286,7 @@
|
||||
<dependency>
|
||||
<groupId>org.signal</groupId>
|
||||
<artifactId>libsignal-server</artifactId>
|
||||
<version>0.86.6</version>
|
||||
<version>0.96.2</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.signal</groupId>
|
||||
|
||||
@@ -79,9 +79,8 @@ storageService.userAuthenticationTokenSharedSecret: AAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
||||
|
||||
zkConfig-libsignal-0.42.serverSecret: ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdef
|
||||
|
||||
genericZkConfig.serverSecret: ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzAA==
|
||||
callingZkConfig.serverSecret: ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzAA==
|
||||
backupsZkConfig.serverSecret: ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzAA==
|
||||
chatZkConfig.serverSecret: ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzAA==
|
||||
|
||||
paymentsService.userAuthenticationTokenSharedSecret: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= # base64-encoded 32-byte secret shared with MobileCoin services used to generate auth tokens for Signal users
|
||||
paymentsService.fixerApiKey: unset
|
||||
@@ -100,3 +99,5 @@ tlsKeyStore.password: unset
|
||||
|
||||
hlrLookup.apiKey: AAAAAAAAAAA
|
||||
hlrLookup.apiSecret: AAAAAAAAAAA
|
||||
|
||||
foundationDbMessages.versionstampCipherKey.0: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=
|
||||
@@ -100,6 +100,9 @@ dynamoDbTables:
|
||||
tableName: Example_DeletedAccounts
|
||||
deletedAccountsLock:
|
||||
tableName: Example_DeletedAccountsLock
|
||||
donationPermits:
|
||||
tableName: Example_DonationPermits
|
||||
expiration: P7D # Duration of time until rows expire
|
||||
issuedReceipts:
|
||||
tableName: Example_IssuedReceipts
|
||||
expiration: P30D # Duration of time until rows expire
|
||||
@@ -125,6 +128,8 @@ dynamoDbTables:
|
||||
expiration: P90D
|
||||
phoneNumberIdentifiers:
|
||||
tableName: Example_PhoneNumberIdentifiers
|
||||
profileAvatars:
|
||||
tableName: Example_ProfileAvatars
|
||||
profiles:
|
||||
tableName: Example_Profiles
|
||||
profilesV2:
|
||||
@@ -313,15 +318,15 @@ storageService:
|
||||
AAAAAAAAAAAAAAAAAAAA
|
||||
-----END CERTIFICATE-----
|
||||
|
||||
zkConfig:
|
||||
serverPublic: ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzAB==
|
||||
serverSecret: secret://zkConfig-libsignal-0.42.serverSecret
|
||||
|
||||
callingZkConfig:
|
||||
serverSecret: secret://callingZkConfig.serverSecret
|
||||
|
||||
backupsZkConfig:
|
||||
serverSecret: secret://backupsZkConfig.serverSecret
|
||||
chatZkConfig:
|
||||
serverSecret: secret://chatZkConfig.serverSecret
|
||||
|
||||
groupsZkConfig:
|
||||
serverPublic: ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzAB==
|
||||
serverSecret: secret://zkConfig-libsignal-0.42.serverSecret
|
||||
|
||||
dynamicConfig:
|
||||
s3Region: a-region
|
||||
@@ -360,8 +365,6 @@ badges:
|
||||
svgs:
|
||||
- light: example-light.svg
|
||||
dark: example-dark.svg
|
||||
badgeIdsEnabledForAll:
|
||||
- TEST
|
||||
receiptLevels:
|
||||
'1': TEST
|
||||
|
||||
@@ -538,3 +541,27 @@ callQualitySurvey:
|
||||
hlrLookup:
|
||||
apiKey: secret://hlrLookup.apiKey
|
||||
apiSecret: secret://hlrLookup.apiSecret
|
||||
|
||||
foundationDbMessages:
|
||||
maxWatchesPerClient: 10000
|
||||
versionstampCipherKeys:
|
||||
0: secret://foundationDbMessages.versionstampCipherKey.0
|
||||
currentVersionstampCipherKey: 0
|
||||
clusters:
|
||||
"messages-0":
|
||||
clusterFileUrl: http://clusterfiles.example.com/messages-0
|
||||
"messages-1":
|
||||
clusterFileUrl: http://clusterfiles.example.com/messages-1
|
||||
"messages-2":
|
||||
clusterFileUrl: http://clusterfiles.example.com/messages-2
|
||||
"messages-3":
|
||||
clusterFileUrl: http://clusterfiles.example.com/messages-3
|
||||
epochs:
|
||||
0:
|
||||
- messages-0
|
||||
- messages-1
|
||||
1:
|
||||
- messages-0
|
||||
- messages-1
|
||||
- messages-2
|
||||
- messages-3
|
||||
+2
-1
@@ -617,7 +617,7 @@
|
||||
<plugin>
|
||||
<groupId>io.github.download-maven-plugin</groupId>
|
||||
<artifactId>download-maven-plugin</artifactId>
|
||||
<version>2.0.0</version>
|
||||
<version>2.1.0</version>
|
||||
|
||||
<executions>
|
||||
<execution>
|
||||
@@ -632,6 +632,7 @@
|
||||
<configuration>
|
||||
<url>https://github.com/apple/foundationdb/releases/download/${foundationdb.version}/libfdb_c.x86_64.so</url>
|
||||
<outputDirectory>${project.build.directory}/jib-extra/usr/lib</outputDirectory>
|
||||
<outputFileName>libfdb_c.so</outputFileName>
|
||||
<sha256>${foundationdb.client-library-sha256}</sha256>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
+34
-11
@@ -17,6 +17,7 @@ import org.whispersystems.textsecuregcm.configuration.AppleAppStoreConfiguration
|
||||
import org.whispersystems.textsecuregcm.configuration.AppleDeviceCheckConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.AttachmentsConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.AwsCredentialsProviderFactory;
|
||||
import org.whispersystems.textsecuregcm.configuration.BackupConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.BadgesConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.BraintreeConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.CallQualitySurveyConfiguration;
|
||||
@@ -34,6 +35,7 @@ import org.whispersystems.textsecuregcm.configuration.ExternalRequestFilterConfi
|
||||
import org.whispersystems.textsecuregcm.configuration.FaultTolerantRedisClientFactory;
|
||||
import org.whispersystems.textsecuregcm.configuration.FaultTolerantRedisClusterFactory;
|
||||
import org.whispersystems.textsecuregcm.configuration.FcmConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.FoundationDbMessagesConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.GcpAttachmentsConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.GenericZkConfig;
|
||||
import org.whispersystems.textsecuregcm.configuration.GooglePlayBillingConfiguration;
|
||||
@@ -66,7 +68,7 @@ import org.whispersystems.textsecuregcm.configuration.VirtualThreadConfiguration
|
||||
import org.whispersystems.textsecuregcm.configuration.ZkConfig;
|
||||
import org.whispersystems.websocket.configuration.WebSocketConfiguration;
|
||||
|
||||
/** @noinspection MismatchedQueryAndUpdateOfCollection, WeakerAccess */
|
||||
// @noinspection MismatchedQueryAndUpdateOfCollection, WeakerAccess
|
||||
public class WhisperServerConfiguration extends Configuration {
|
||||
|
||||
@NotNull
|
||||
@@ -129,6 +131,11 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
@JsonProperty
|
||||
private GcpAttachmentsConfiguration gcpAttachments;
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
@JsonProperty
|
||||
private BackupConfiguration backup = new BackupConfiguration();
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
@JsonProperty
|
||||
@@ -219,11 +226,6 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
@JsonProperty
|
||||
private PaymentsServiceConfiguration paymentsService;
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
private ZkConfig zkConfig;
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
@@ -232,7 +234,12 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
private GenericZkConfig backupsZkConfig;
|
||||
private GenericZkConfig chatZkConfig;
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
private ZkConfig groupsZkConfig;
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@@ -361,6 +368,11 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
@JsonProperty
|
||||
private ChangeNumberConfiguration changeNumber = new ChangeNumberConfiguration(Duration.ofHours(1));
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
private FoundationDbMessagesConfiguration foundationDbMessages;
|
||||
|
||||
public TlsKeyStoreConfiguration getTlsKeyStoreConfiguration() {
|
||||
return tlsKeyStore;
|
||||
}
|
||||
@@ -417,6 +429,10 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
return gcpAttachments;
|
||||
}
|
||||
|
||||
public BackupConfiguration getBackupConfiguration() {
|
||||
return backup;
|
||||
}
|
||||
|
||||
public FaultTolerantRedisClusterFactory getCacheClusterConfiguration() {
|
||||
return cacheCluster;
|
||||
}
|
||||
@@ -481,16 +497,19 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
return paymentsService;
|
||||
}
|
||||
|
||||
public ZkConfig getZkConfig() {
|
||||
return zkConfig;
|
||||
/// ZK secret limited to Chat Service
|
||||
public GenericZkConfig getChatZkConfig() {
|
||||
return chatZkConfig;
|
||||
}
|
||||
|
||||
/// ZK secret shared with Calling Service
|
||||
public GenericZkConfig getCallingZkConfig() {
|
||||
return callingZkConfig;
|
||||
}
|
||||
|
||||
public GenericZkConfig getBackupsZkConfig() {
|
||||
return backupsZkConfig;
|
||||
/// ZK secret shared with Groups Service
|
||||
public ZkConfig getGroupsZkConfig() {
|
||||
return groupsZkConfig;
|
||||
}
|
||||
|
||||
public RemoteConfigConfiguration getRemoteConfigConfiguration() {
|
||||
@@ -600,4 +619,8 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
public ChangeNumberConfiguration getChangeNumber() {
|
||||
return changeNumber;
|
||||
}
|
||||
|
||||
public FoundationDbMessagesConfiguration getFoundationDbMessagesConfiguration() {
|
||||
return foundationDbMessages;
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,8 @@ package org.whispersystems.textsecuregcm;
|
||||
import static java.util.Objects.requireNonNull;
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.apple.foundationdb.Database;
|
||||
import com.apple.foundationdb.FDB;
|
||||
import com.google.common.collect.Lists;
|
||||
import com.webauthn4j.appattest.DeviceCheckManager;
|
||||
import io.dropwizard.auth.AuthDynamicFeature;
|
||||
@@ -44,6 +46,8 @@ import io.netty.resolver.dns.DnsNameResolverBuilder;
|
||||
import io.netty.util.Mapping;
|
||||
import jakarta.servlet.DispatcherType;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.SocketAddress;
|
||||
import java.net.http.HttpClient;
|
||||
@@ -53,6 +57,7 @@ import java.time.Duration;
|
||||
import java.util.Collections;
|
||||
import java.util.EnumSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.ServiceLoader;
|
||||
import java.util.Set;
|
||||
@@ -63,7 +68,9 @@ import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.SynchronousQueue;
|
||||
import java.util.concurrent.ThreadPoolExecutor;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
import javax.annotation.Nullable;
|
||||
import org.eclipse.jetty.ee10.websocket.server.config.JettyWebSocketServletContainerInitializer;
|
||||
import org.eclipse.jetty.websocket.core.WebSocketExtensionRegistry;
|
||||
import org.eclipse.jetty.websocket.core.server.WebSocketServerComponents;
|
||||
@@ -169,13 +176,16 @@ import org.whispersystems.textsecuregcm.grpc.MessageDispatcher;
|
||||
import org.whispersystems.textsecuregcm.grpc.MessagesAnonymousGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.MessagesGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.MetricServerInterceptor;
|
||||
import org.whispersystems.textsecuregcm.grpc.OneTimeDonationsGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.PaymentsGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.ProductConfigurationGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.ProfileAnonymousGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.ProfileGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.RequestAttributesInterceptor;
|
||||
import org.whispersystems.textsecuregcm.grpc.SubscriptionsGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.ValidatingInterceptor;
|
||||
import org.whispersystems.textsecuregcm.grpc.net.ManagedGrpcServer;
|
||||
import org.whispersystems.textsecuregcm.grpc.net.ManagedEventLoopGroup;
|
||||
import org.whispersystems.textsecuregcm.grpc.net.ManagedGrpcServer;
|
||||
import org.whispersystems.textsecuregcm.grpc.net.OmnibusH2Server;
|
||||
import org.whispersystems.textsecuregcm.grpc.net.OmnibusRouter;
|
||||
import org.whispersystems.textsecuregcm.grpc.net.SniMapper;
|
||||
@@ -226,7 +236,6 @@ import org.whispersystems.textsecuregcm.redis.ConnectionEventLogger;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import org.whispersystems.textsecuregcm.registration.RegistrationServiceClient;
|
||||
import org.whispersystems.textsecuregcm.s3.PolicySigner;
|
||||
import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
|
||||
import org.whispersystems.textsecuregcm.s3.S3MonitoringSupplier;
|
||||
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
|
||||
@@ -244,7 +253,10 @@ import org.whispersystems.textsecuregcm.storage.ChangeNumberWaitingPeriodManager
|
||||
import org.whispersystems.textsecuregcm.storage.ChangeNumberWaitingPeriods;
|
||||
import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ClientReleases;
|
||||
import org.whispersystems.textsecuregcm.storage.DonationPermits;
|
||||
import org.whispersystems.textsecuregcm.storage.DonationPermitsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.storage.FoundationDbVersion;
|
||||
import org.whispersystems.textsecuregcm.storage.IssuedReceiptsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.KeysManager;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesCache;
|
||||
@@ -254,6 +266,7 @@ import org.whispersystems.textsecuregcm.storage.OneTimeDonationsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.PagedSingleUseKEMPreKeyStore;
|
||||
import org.whispersystems.textsecuregcm.storage.PersistentTimer;
|
||||
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
|
||||
import org.whispersystems.textsecuregcm.storage.ProfileAvatars;
|
||||
import org.whispersystems.textsecuregcm.storage.Profiles;
|
||||
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ProfilesV2;
|
||||
@@ -275,6 +288,8 @@ import org.whispersystems.textsecuregcm.storage.VerificationSessions;
|
||||
import org.whispersystems.textsecuregcm.storage.devicecheck.AppleDeviceCheckManager;
|
||||
import org.whispersystems.textsecuregcm.storage.devicecheck.AppleDeviceCheckTrustAnchor;
|
||||
import org.whispersystems.textsecuregcm.storage.devicecheck.AppleDeviceChecks;
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStore;
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.VersionstampUUIDCipher;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.AppleAppStoreClient;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.AppleAppStoreManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.BankMandateTranslator;
|
||||
@@ -302,6 +317,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.ClearExpiredFoundationDbMessagesCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.ClearIssuedReceiptRedemptionsCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.CopyToS3Command;
|
||||
import org.whispersystems.textsecuregcm.workers.DeleteUserCommand;
|
||||
@@ -331,7 +347,6 @@ import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
|
||||
import software.amazon.awssdk.services.s3.S3AsyncClient;
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
public class WhisperServerService extends Application<WhisperServerConfiguration> {
|
||||
|
||||
@@ -378,6 +393,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
bootstrap.addCommand(new NotifyIdleDevicesCommand());
|
||||
bootstrap.addCommand(new ClearIssuedReceiptRedemptionsCommand());
|
||||
bootstrap.addCommand(new CopyToS3Command());
|
||||
bootstrap.addCommand(new ClearExpiredFoundationDbMessagesCommand(Clock.systemUTC()));
|
||||
|
||||
bootstrap.addCommand(new ProcessScheduledJobsServiceCommand("process-idle-device-notification-jobs",
|
||||
"Processes scheduled jobs to send notifications to idle devices",
|
||||
@@ -400,7 +416,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
@Override
|
||||
public void run(WhisperServerConfiguration config, Environment environment) throws Exception {
|
||||
final Clock clock = Clock.systemUTC();
|
||||
final int availableProcessors = Runtime.getRuntime().availableProcessors();
|
||||
|
||||
final AwsCredentialsProvider awsCredentialsProvider = config.getAwsCredentialsConfiguration().build();
|
||||
|
||||
@@ -461,6 +476,39 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
final DynamoDbClient dynamoDbClient = config.getDynamoDbClientConfiguration()
|
||||
.buildSyncClient(awsCredentialsProvider, new MicrometerAwsSdkMetricPublisher(awsSdkMetricsExecutor, "dynamoDbSync"));
|
||||
|
||||
final FDB fdb = FDB.selectAPIVersion(FoundationDbVersion.getFoundationDbApiVersion());
|
||||
|
||||
// Jetty and the FoundationDB client both register shutdown hooks to begin shutdown/cleanup operations. There isn't
|
||||
// a good way to coordinate or enforce ordering between shutdown hooks, and so the two processes will race.
|
||||
// Generally, FoundationDB will shut down before Jetty does, meaning we'll still be trying to serve requests that
|
||||
// require talking to FoundationDB even though FoundationDB has shut down. To avoid that scenario, we disabled
|
||||
// FoundationDB's shutdown hook and let the JVM terminate its (daemon) threads at exit. This isn't as graceful as
|
||||
// we'd like, but is the least bad option given current constraints.
|
||||
fdb.disableShutdownHook();
|
||||
|
||||
final Map<Integer, List<Database>> messageDatabasesByEpoch;
|
||||
{
|
||||
final Map<String, Database> databasesByName =
|
||||
config.getFoundationDbMessagesConfiguration().clusters().entrySet().stream()
|
||||
.collect(Collectors.toUnmodifiableMap(Map.Entry::getKey,
|
||||
entry -> {
|
||||
try {
|
||||
final Database database = entry.getValue().build(fdb);
|
||||
database.options().setMaxWatches(config.getFoundationDbMessagesConfiguration().maxWatchesPerClient());
|
||||
|
||||
return database;
|
||||
} catch (final IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
}));
|
||||
|
||||
messageDatabasesByEpoch = config.getFoundationDbMessagesConfiguration().epochs().entrySet().stream()
|
||||
.collect(Collectors.toUnmodifiableMap(Map.Entry::getKey,
|
||||
entry -> entry.getValue().stream()
|
||||
.map(databasesByName::get)
|
||||
.toList()));
|
||||
}
|
||||
|
||||
final AwsCredentialsProvider cdnCredentialsProvider = config.getCdnConfiguration().credentials().build();
|
||||
final S3AsyncClient asyncCdnS3Client = S3AsyncClient.builder()
|
||||
.credentialsProvider(cdnCredentialsProvider)
|
||||
@@ -494,6 +542,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
Profiles profilesV1 = new Profiles(dynamoDbClient, dynamoDbAsyncClient,
|
||||
config.getDynamoDbTables().getProfilesV1().getTableName());
|
||||
ProfilesV2 profiles = new ProfilesV2(dynamoDbClient, dynamoDbAsyncClient, config.getDynamoDbTables().getProfilesV2().getTableName());
|
||||
ProfileAvatars profileAvatars = new ProfileAvatars(dynamoDbClient,
|
||||
config.getDynamoDbTables().getProfileAvatars().getTableName(), RemoveExpiredAccountsCommand.MAX_IDLE_DURATION, clock);
|
||||
|
||||
S3AsyncClient asyncKeysS3Client = S3AsyncClient.builder()
|
||||
.credentialsProvider(awsCredentialsProvider)
|
||||
@@ -574,6 +624,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
.threads(16).build();
|
||||
final ScheduledExecutorService registrationIdentityTokenRefreshExecutor =
|
||||
ScheduledExecutorServiceBuilder.of(environment, "registrationIdentityTokenRefresh").threads(1).build();
|
||||
final ScheduledExecutorService presenceRenewalExecutor =
|
||||
ScheduledExecutorServiceBuilder.of(environment, "presenceRenewal").threads(4).build();
|
||||
|
||||
Scheduler messageDeliveryScheduler = Schedulers.fromExecutorService(
|
||||
ExecutorServiceBuilder.of(environment, "messageDelivery")
|
||||
@@ -592,10 +644,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
.workQueue(receiptSenderQueue)
|
||||
.rejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy())
|
||||
.build();
|
||||
ExecutorService registrationCallbackExecutor = ExecutorServiceBuilder.of(environment, "registration")
|
||||
.maxThreads(2)
|
||||
.minThreads(2)
|
||||
.build();
|
||||
ExecutorService accountLockExecutor = ExecutorServiceBuilder.of(environment, "accountLock")
|
||||
.minThreads(8)
|
||||
.maxThreads(8)
|
||||
@@ -677,7 +725,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
retryExecutor);
|
||||
|
||||
RegistrationServiceClient registrationServiceClient = config.getRegistrationServiceConfiguration()
|
||||
.build(environment, registrationCallbackExecutor, registrationIdentityTokenRefreshExecutor);
|
||||
.build(environment, registrationIdentityTokenRefreshExecutor);
|
||||
KeyTransparencyServiceClient keyTransparencyServiceClient = new KeyTransparencyServiceClient(
|
||||
config.getKeyTransparencyServiceConfiguration().host(),
|
||||
config.getKeyTransparencyServiceConfiguration().port(),
|
||||
@@ -700,10 +748,16 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
storageServiceExecutor, retryExecutor, config.getSecureStorageServiceConfiguration());
|
||||
DisconnectionRequestManager disconnectionRequestManager = new DisconnectionRequestManager(pubsubClient,
|
||||
disconnectionRequestListenerExecutor, retryExecutor);
|
||||
ProfilesManager profilesManager = new ProfilesManager(profilesV1, profiles, cacheCluster, retryExecutor, asyncCdnS3Client,
|
||||
ProfilesManager profilesManager = new ProfilesManager(profilesV1, profiles, profileAvatars, cacheCluster, retryExecutor, asyncCdnS3Client,
|
||||
config.getCdnConfiguration().bucket());
|
||||
MessagesCache messagesCache = new MessagesCache(messagesCluster, messageDeliveryScheduler,
|
||||
messageDeletionAsyncExecutor, retryExecutor, clock);
|
||||
final FoundationDbMessageStore foundationDbMessageStore = new FoundationDbMessageStore(messageDatabasesByEpoch,
|
||||
config.getFoundationDbMessagesConfiguration().activeEpoch(),
|
||||
new VersionstampUUIDCipher(config.getFoundationDbMessagesConfiguration().currentVersionstampCipherKey(),
|
||||
config.getFoundationDbMessagesConfiguration().versionstampCipherKeys().get(config.getFoundationDbMessagesConfiguration().currentVersionstampCipherKey()).value()),
|
||||
presenceRenewalExecutor,
|
||||
Clock.systemUTC());
|
||||
ClientReleaseManager clientReleaseManager = new ClientReleaseManager(clientReleases,
|
||||
recurringJobExecutor,
|
||||
config.getClientReleaseConfiguration().refreshInterval(),
|
||||
@@ -712,8 +766,9 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
config.getReportMessageConfiguration().getCounterTtl());
|
||||
RedisMessageAvailabilityManager redisMessageAvailabilityManager =
|
||||
new RedisMessageAvailabilityManager(messagesCluster, clientEventExecutor, asyncOperationQueueingExecutor);
|
||||
MessagesManager messagesManager = new MessagesManager(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager,
|
||||
reportMessageManager, messageDeletionAsyncExecutor, Clock.systemUTC());
|
||||
MessagesManager messagesManager =
|
||||
new MessagesManager(messagesDynamoDb, messagesCache, foundationDbMessageStore, redisMessageAvailabilityManager,
|
||||
reportMessageManager, messageDeletionAsyncExecutor, Clock.systemUTC(), experimentEnrollmentManager);
|
||||
final ChangeNumberWaitingPeriods changeNumberWaitingPeriods = new ChangeNumberWaitingPeriods(
|
||||
config.getDynamoDbTables().getChangeNumberWaitingPeriods().getTableName(), dynamoDbClient);
|
||||
final ChangeNumberWaitingPeriodManager changeNumberWaitingPeriodManager = new ChangeNumberWaitingPeriodManager(
|
||||
@@ -742,6 +797,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
config.getDynamoDbTables().getIssuedReceipts().getmaxIssuedReceiptsPerPaymentId());
|
||||
OneTimeDonationsManager oneTimeDonationsManager = new OneTimeDonationsManager(
|
||||
config.getDynamoDbTables().getOnetimeDonations().getTableName(), config.getDynamoDbTables().getOnetimeDonations().getExpiration(), dynamoDbClient);
|
||||
DonationPermits donationPermits = new DonationPermits(
|
||||
config.getDynamoDbTables().getDonationPermits().getTableName(), config.getDynamoDbTables().getDonationPermits().getExpiration(), dynamoDbClient);
|
||||
RedeemedReceiptsManager redeemedReceiptsManager = new RedeemedReceiptsManager(clock,
|
||||
config.getDynamoDbTables().getRedeemedReceipts().getTableName(),
|
||||
dynamoDbClient,
|
||||
@@ -850,23 +907,28 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
config.getGcpAttachmentsConfiguration().pathPrefix(),
|
||||
config.getGcpAttachmentsConfiguration().rsaSigningKey().value());
|
||||
|
||||
PostPolicyGenerator profileCdnPolicyGenerator = new PostPolicyGenerator(config.getCdnConfiguration().region(),
|
||||
config.getCdnConfiguration().bucket(), config.getCdnConfiguration().credentials().accessKeyId().value());
|
||||
PolicySigner profileCdnPolicySigner = new PolicySigner(
|
||||
config.getCdnConfiguration().credentials().secretAccessKey().value(),
|
||||
config.getCdnConfiguration().region());
|
||||
final PostPolicyGenerator profileCdnPolicyGenerator = new PostPolicyGenerator(config.getCdnConfiguration().region(),
|
||||
config.getCdnConfiguration().bucket(),
|
||||
config.getCdnConfiguration().credentials().accessKeyId().value(),
|
||||
config.getCdnConfiguration().credentials().secretAccessKey().value());
|
||||
|
||||
ServerSecretParams zkSecretParams = new ServerSecretParams(config.getZkConfig().serverSecret().value());
|
||||
final PostPolicyGenerator stickerPolicyGenerator = new PostPolicyGenerator(config.getCdnConfiguration().region(),
|
||||
config.getCdnConfiguration().bucket(),
|
||||
config.getCdnConfiguration().credentials().accessKeyId().value(),
|
||||
config.getCdnConfiguration().credentials().secretAccessKey().value());
|
||||
|
||||
ServerSecretParams groupZkSecretParams = new ServerSecretParams(config.getGroupsZkConfig().serverSecret().value());
|
||||
GenericServerSecretParams callingGenericZkSecretParams = new GenericServerSecretParams(config.getCallingZkConfig().serverSecret().value());
|
||||
GenericServerSecretParams backupsGenericZkSecretParams = new GenericServerSecretParams(config.getBackupsZkConfig().serverSecret().value());
|
||||
ServerZkProfileOperations zkProfileOperations = new ServerZkProfileOperations(zkSecretParams);
|
||||
ServerZkAuthOperations zkAuthOperations = new ServerZkAuthOperations(zkSecretParams);
|
||||
ServerZkReceiptOperations zkReceiptOperations = new ServerZkReceiptOperations(zkSecretParams);
|
||||
GenericServerSecretParams chatGenericZkSecretParams = new GenericServerSecretParams(config.getChatZkConfig().serverSecret().value());
|
||||
ServerZkProfileOperations zkProfileOperations = new ServerZkProfileOperations(groupZkSecretParams);
|
||||
ServerZkAuthOperations zkAuthOperations = new ServerZkAuthOperations(groupZkSecretParams);
|
||||
// ZK receipts are not actually shared with ZK groups, but use the same extensible parameters object for legacy reasons
|
||||
ServerZkReceiptOperations zkReceiptOperations = new ServerZkReceiptOperations(groupZkSecretParams);
|
||||
|
||||
TusAttachmentGenerator tusAttachmentGenerator = new TusAttachmentGenerator(config.getTus());
|
||||
Cdn3BackupCredentialGenerator cdn3BackupCredentialGenerator = new Cdn3BackupCredentialGenerator(config.getTus());
|
||||
BackupAuthManager backupAuthManager = new BackupAuthManager(experimentEnrollmentManager, rateLimiters,
|
||||
accountsManager, zkReceiptOperations, redeemedReceiptsManager, backupsGenericZkSecretParams, clock);
|
||||
accountsManager, zkReceiptOperations, redeemedReceiptsManager, chatGenericZkSecretParams, clock);
|
||||
BackupsDb backupsDb = new BackupsDb(
|
||||
dynamoDbAsyncClient,
|
||||
config.getDynamoDbTables().getBackups().getTableName(),
|
||||
@@ -877,7 +939,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
config.getCdn3StorageManagerConfiguration());
|
||||
BackupManager backupManager = new BackupManager(
|
||||
backupsDb,
|
||||
backupsGenericZkSecretParams,
|
||||
chatGenericZkSecretParams,
|
||||
rateLimiters,
|
||||
tusAttachmentGenerator,
|
||||
cdn3BackupCredentialGenerator,
|
||||
@@ -885,7 +947,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
svrbCredentialsGenerator,
|
||||
secureValueRecoveryBClient,
|
||||
clock,
|
||||
dynamicConfigurationManager);
|
||||
config.getBackupConfiguration());
|
||||
final BackupMetrics backupMetrics = new BackupMetrics();
|
||||
|
||||
final AppleDeviceChecks appleDeviceChecks = new AppleDeviceChecks(
|
||||
@@ -902,6 +964,13 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
config.getAppleDeviceCheck().teamId(),
|
||||
config.getAppleDeviceCheck().bundleId());
|
||||
|
||||
final DonationPermitsManager donationPermitsManager = new DonationPermitsManager(donationPermits, groupZkSecretParams,
|
||||
clock);
|
||||
|
||||
final SubscriptionManager subscriptionManager = new SubscriptionManager(subscriptions,
|
||||
List.of(stripeManager, braintreeManager, googlePlayBillingManager, appleAppStoreManager),
|
||||
zkReceiptOperations, issuedReceiptsManager);
|
||||
|
||||
final List<SpamFilter> spamFilters = ServiceLoader.load(SpamFilter.class)
|
||||
.stream()
|
||||
.map(ServiceLoader.Provider::get)
|
||||
@@ -988,7 +1057,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
config.getExternalRequestFilterConfiguration().grpcMethods());
|
||||
final RequireAuthenticationInterceptor requireAuthenticationInterceptor = new RequireAuthenticationInterceptor(accountAuthenticator);
|
||||
final ProhibitAuthenticationInterceptor prohibitAuthenticationInterceptor = new ProhibitAuthenticationInterceptor();
|
||||
final GroupSendTokenUtil groupSendTokenUtil = new GroupSendTokenUtil(zkSecretParams, Clock.systemUTC());
|
||||
final GroupSendTokenUtil groupSendTokenUtil = new GroupSendTokenUtil(groupZkSecretParams, Clock.systemUTC());
|
||||
final MessageMetrics messageMetrics = new MessageMetrics();
|
||||
final MessageDispatcher messageDispatcher = new MessageDispatcher(receiptSender, messagesManager, messageMetrics,
|
||||
pushNotificationManager, pushNotificationScheduler, messageDeliveryLoopMonitor, disconnectionRequestManager,
|
||||
@@ -1001,19 +1070,23 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
config.getDeliveryCertificate().embedSigner());
|
||||
|
||||
final List<ServerServiceDefinition> authenticatedServices = Stream.of(
|
||||
new AccountsGrpcService(accountsManager, rateLimiters, usernameHashZkProofVerifier, registrationRecoveryPasswordsManager),
|
||||
new AccountsGrpcService(accountsManager, rateLimiters, usernameHashZkProofVerifier, registrationRecoveryPasswordsManager, Clock.systemUTC()),
|
||||
new CallingGrpcService(cloudflareTurnCredentialsManager, rateLimiters),
|
||||
new CredentialsGrpcService(accountsManager, certificateGenerator, zkAuthOperations, callingGenericZkSecretParams, rateLimiters, Clock.systemUTC(), ExternalServiceDefinitions.createExternalServiceList(config, Clock.systemUTC())),
|
||||
new KeysGrpcService(accountsManager, keysManager, rateLimiters),
|
||||
new ProfileGrpcService(clock, accountsManager, profilesManager, dynamicConfigurationManager, config.getBadges(), profileCdnPolicyGenerator, profileCdnPolicySigner, profileBadgeConverter, rateLimiters),
|
||||
new ProfileGrpcService(clock, accountsManager, profilesManager, dynamicConfigurationManager, config.getBadges(), profileCdnPolicyGenerator, chatGenericZkSecretParams, profileBadgeConverter, rateLimiters),
|
||||
new MessagesGrpcService(accountsManager, rateLimiters, messageSender, messageByteLimitCardinalityEstimator, spamChecker, messageDispatcher, Clock.systemUTC()),
|
||||
new BackupsGrpcService(accountsManager, backupAuthManager, backupMetrics),
|
||||
new DevicesGrpcService(accountsManager),
|
||||
new AttachmentsGrpcService(experimentEnrollmentManager, rateLimiters,
|
||||
gcsAttachmentGenerator, tusAttachmentGenerator, config.getAttachments().maxAttachmentUploadSizeInBytes()),
|
||||
new AttachmentsGrpcService(experimentEnrollmentManager, rateLimiters, gcsAttachmentGenerator,
|
||||
tusAttachmentGenerator, stickerPolicyGenerator,
|
||||
config.getAttachments().maxAttachmentUploadSizeInBytes(), Clock.systemUTC()),
|
||||
new PaymentsGrpcService(currencyManager),
|
||||
new ChallengeGrpcService(accountsManager, rateLimitChallengeManager, challengeConstraintChecker),
|
||||
new DonationsGrpcService(clock, zkReceiptOperations, redeemedReceiptsManager, accountsManager, config.getBadges(), ReceiptCredentialPresentation::new))
|
||||
new DonationsGrpcService(clock, zkReceiptOperations, redeemedReceiptsManager, accountsManager, config.getBadges(), ReceiptCredentialPresentation::new, donationPermitsManager, rateLimiters),
|
||||
new ProductConfigurationGrpcService(config.getSubscription(), config.getOneTimeDonations(),
|
||||
List.of(stripeManager, braintreeManager), profileBadgeConverter,
|
||||
config.getBackupConfiguration().maxTotalMediaSize()))
|
||||
.map(bindableService -> ServerInterceptors.intercept(bindableService,
|
||||
// Note: interceptors run in the reverse order they are added; the remote deprecation filter
|
||||
// depends on the user-agent context so it has to come first here!
|
||||
@@ -1029,11 +1102,16 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
final List<ServerServiceDefinition> unauthenticatedServices = Stream.of(
|
||||
new AccountsAnonymousGrpcService(accountsManager, rateLimiters),
|
||||
new CallQualitySurveyGrpcService(callQualitySurveyManager, rateLimiters),
|
||||
new KeysAnonymousGrpcService(accountsManager, keysManager, zkSecretParams, Clock.systemUTC()),
|
||||
new ProfileAnonymousGrpcService(accountsManager, profilesManager, profileBadgeConverter, zkSecretParams),
|
||||
new KeysAnonymousGrpcService(accountsManager, keysManager, groupZkSecretParams, Clock.systemUTC()),
|
||||
new ProfileAnonymousGrpcService(accountsManager, profilesManager, profileBadgeConverter, profileCdnPolicyGenerator, chatGenericZkSecretParams, groupZkSecretParams, rateLimiters, clock),
|
||||
new MessagesAnonymousGrpcService(accountsManager, rateLimiters, messageSender, groupSendTokenUtil, messageByteLimitCardinalityEstimator, spamChecker, Clock.systemUTC()),
|
||||
new BackupsAnonymousGrpcService(backupManager, backupMetrics, config.getAttachments().maxAttachmentUploadSizeInBytes(), config.getAttachments().maxMessageBackupUploadSizeInBytes()),
|
||||
new CredentialsAnonymousGrpcService(accountsManager, ExternalServiceDefinitions.SVR.generatorFactory().apply(config, Clock.systemUTC())))
|
||||
new CredentialsAnonymousGrpcService(accountsManager, ExternalServiceDefinitions.SVR.generatorFactory().apply(config, Clock.systemUTC())),
|
||||
new SubscriptionsGrpcService(clock, config.getSubscription(), subscriptionManager, donationPermitsManager,
|
||||
stripeManager, braintreeManager, googlePlayBillingManager, appleAppStoreManager, bankMandateTranslator),
|
||||
new OneTimeDonationsGrpcService(config.getOneTimeDonations(), stripeManager, braintreeManager,
|
||||
payPalDonationsTranslator, oneTimeDonationsManager, issuedReceiptsManager,
|
||||
zkReceiptOperations, clock, rateLimiters, donationPermitsManager))
|
||||
.map(bindableService -> ServerInterceptors.intercept(bindableService,
|
||||
// Note: interceptors run in the reverse order they are added; the remote deprecation filter
|
||||
// depends on the user-agent context so it has to come first here!
|
||||
@@ -1074,6 +1152,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
omnibusNioEventLoopGroup.getEventLoopGroup(),
|
||||
omnibusLocalEventLoopGroup.getEventLoopGroup(),
|
||||
new InetSocketAddress(config.getGrpc().bindAddress(), config.getGrpc().port()), omnibusRouter,
|
||||
() -> dynamicConfigurationManager.getConfiguration().getOmnibus(),
|
||||
config.getGrpc().idleTimeout());
|
||||
|
||||
environment.lifecycle().manage(omnibusLocalEventLoopGroup);
|
||||
@@ -1163,39 +1242,34 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
config.getDeviceCheck().backupRedemptionDuration()),
|
||||
new DirectoryV2Controller(directoryV2CredentialsGenerator),
|
||||
new DonationController(clock, zkReceiptOperations, redeemedReceiptsManager, accountsManager, config.getBadges(),
|
||||
ReceiptCredentialPresentation::new),
|
||||
new KeysController(rateLimiters, keysManager, accountsManager, zkSecretParams, Clock.systemUTC()),
|
||||
ReceiptCredentialPresentation::new, donationPermitsManager, rateLimiters),
|
||||
new KeysController(rateLimiters, keysManager, accountsManager, groupZkSecretParams, Clock.systemUTC()),
|
||||
new KeyTransparencyController(keyTransparencyServiceClient),
|
||||
new MessageController(rateLimiters, messageByteLimitCardinalityEstimator, messageSender, accountsManager,
|
||||
phoneNumberIdentifiers, reportMessageManager, zkSecretParams, spamChecker, Clock.systemUTC()),
|
||||
phoneNumberIdentifiers, reportMessageManager, groupZkSecretParams, spamChecker, Clock.systemUTC()),
|
||||
new PaymentsController(currencyManager, paymentsCredentialsGenerator),
|
||||
new ProfileController(clock, rateLimiters, accountsManager, profilesManager, dynamicConfigurationManager,
|
||||
profileBadgeConverter, config.getBadges(), profileCdnPolicyGenerator, profileCdnPolicySigner,
|
||||
zkSecretParams, zkProfileOperations, batchIdentityCheckExecutor),
|
||||
profileBadgeConverter, config.getBadges(), profileCdnPolicyGenerator,
|
||||
groupZkSecretParams, zkProfileOperations, batchIdentityCheckExecutor),
|
||||
new ProvisioningController(rateLimiters, provisioningManager),
|
||||
new RegistrationController(accountsManager, phoneVerificationTokenManager, registrationLockVerificationManager,
|
||||
rateLimiters, registrationFraudChecker),
|
||||
new RemoteConfigController(remoteConfigsManager, config.getRemoteConfigConfiguration().globalConfig()),
|
||||
new SecureStorageController(storageCredentialsGenerator),
|
||||
new SecureValueRecovery2Controller(svr2CredentialsGenerator, accountsManager),
|
||||
new StickerController(rateLimiters, config.getCdnConfiguration().credentials().accessKeyId().value(),
|
||||
config.getCdnConfiguration().credentials().secretAccessKey().value(), config.getCdnConfiguration().region(),
|
||||
config.getCdnConfiguration().bucket()),
|
||||
new StickerController(rateLimiters, stickerPolicyGenerator, Clock.systemUTC()),
|
||||
new VerificationController(registrationServiceClient, new VerificationSessionManager(verificationSessions),
|
||||
pushNotificationManager, registrationCaptchaManager, registrationRecoveryPasswordsManager,
|
||||
phoneNumberIdentifiers, rateLimiters, accountsManager, carrierDataProvider, registrationFraudChecker,
|
||||
dynamicConfigurationManager, experimentEnrollmentManager, clock)
|
||||
dynamicConfigurationManager, experimentEnrollmentManager, clock),
|
||||
new SubscriptionController(clock, config.getSubscription(), config.getOneTimeDonations(),
|
||||
subscriptionManager, stripeManager, braintreeManager, googlePlayBillingManager, appleAppStoreManager,
|
||||
profileBadgeConverter, bankMandateTranslator, donationPermitsManager,
|
||||
config.getBackupConfiguration().maxTotalMediaSize()),
|
||||
new OneTimeDonationController(clock, config.getOneTimeDonations(), stripeManager, braintreeManager,
|
||||
payPalDonationsTranslator, zkReceiptOperations, issuedReceiptsManager, oneTimeDonationsManager,
|
||||
donationPermitsManager)
|
||||
);
|
||||
if (config.getSubscription() != null && config.getOneTimeDonations() != null) {
|
||||
SubscriptionManager subscriptionManager = new SubscriptionManager(subscriptions,
|
||||
List.of(stripeManager, braintreeManager, googlePlayBillingManager, appleAppStoreManager),
|
||||
zkReceiptOperations, issuedReceiptsManager);
|
||||
commonControllers.add(new SubscriptionController(clock, config.getSubscription(), config.getOneTimeDonations(),
|
||||
subscriptionManager, stripeManager, braintreeManager, googlePlayBillingManager, appleAppStoreManager,
|
||||
profileBadgeConverter, bankMandateTranslator, dynamicConfigurationManager));
|
||||
commonControllers.add(new OneTimeDonationController(clock, config.getOneTimeDonations(), stripeManager, braintreeManager,
|
||||
payPalDonationsTranslator, zkReceiptOperations, issuedReceiptsManager, oneTimeDonationsManager));
|
||||
}
|
||||
|
||||
for (Object controller : commonControllers) {
|
||||
environment.jersey().register(controller);
|
||||
@@ -1310,7 +1384,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
static void main(String[] args) throws Exception {
|
||||
new WhisperServerService().run(args);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.auth;
|
||||
|
||||
import jakarta.ws.rs.WebApplicationException;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import java.util.Base64;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.donation.DonationPermit;
|
||||
|
||||
public record DonationPermitHeader(DonationPermit permit) {
|
||||
|
||||
public static DonationPermitHeader valueOf(String header) {
|
||||
try {
|
||||
return new DonationPermitHeader(new DonationPermit(Base64.getDecoder().decode(header)));
|
||||
} catch (InvalidInputException | IllegalArgumentException e) {
|
||||
// Base64 throws IllegalArgumentException; DonationPermit ctor throws InvalidInputException
|
||||
throw new WebApplicationException(e, Response.Status.UNAUTHORIZED);
|
||||
}
|
||||
}
|
||||
}
|
||||
+5
-15
@@ -16,10 +16,10 @@ import jakarta.ws.rs.core.Response;
|
||||
import java.security.MessageDigest;
|
||||
import java.time.Duration;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CancellationException;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import javax.annotation.Nullable;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.entities.PhoneVerificationRequest;
|
||||
@@ -28,7 +28,6 @@ import org.whispersystems.textsecuregcm.registration.RegistrationServiceClient;
|
||||
import org.whispersystems.textsecuregcm.spam.RegistrationRecoveryChecker;
|
||||
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
|
||||
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
public class PhoneVerificationTokenManager {
|
||||
|
||||
@@ -90,11 +89,10 @@ public class PhoneVerificationTokenManager {
|
||||
return verificationType;
|
||||
}
|
||||
|
||||
private void verifyBySessionId(final String number, final byte[] sessionId) throws InterruptedException {
|
||||
private void verifyBySessionId(final String number, final byte[] sessionId) {
|
||||
try {
|
||||
final RegistrationServiceSession session = registrationServiceClient
|
||||
.getSession(sessionId, REGISTRATION_RPC_TIMEOUT)
|
||||
.get(VERIFICATION_TIMEOUT_SECONDS, TimeUnit.SECONDS)
|
||||
.orElseThrow(() -> new NotAuthorizedException("session not verified"));
|
||||
|
||||
if (!MessageDigest.isEqual(number.getBytes(), session.number().getBytes())) {
|
||||
@@ -103,19 +101,11 @@ public class PhoneVerificationTokenManager {
|
||||
if (!session.verified()) {
|
||||
throw new NotAuthorizedException("session not verified");
|
||||
}
|
||||
} catch (final ExecutionException e) {
|
||||
|
||||
if (e.getCause() instanceof StatusRuntimeException grpcRuntimeException) {
|
||||
if (grpcRuntimeException.getStatus().getCode() == Status.Code.INVALID_ARGUMENT) {
|
||||
throw new BadRequestException();
|
||||
}
|
||||
} catch (final StatusRuntimeException e) {
|
||||
if (e.getStatus().getCode() == Status.Code.INVALID_ARGUMENT) {
|
||||
throw new BadRequestException();
|
||||
}
|
||||
|
||||
logger.error("Registration service failure", e);
|
||||
throw new ServerErrorException(Response.Status.SERVICE_UNAVAILABLE);
|
||||
|
||||
} catch (final CancellationException | TimeoutException e) {
|
||||
|
||||
logger.error("Registration service failure", e);
|
||||
throw new ServerErrorException(Response.Status.SERVICE_UNAVAILABLE);
|
||||
}
|
||||
|
||||
@@ -23,6 +23,7 @@ import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
import java.util.function.Function;
|
||||
import javax.annotation.Nullable;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.signal.libsignal.protocol.ecc.ECKeyPair;
|
||||
import org.signal.libsignal.protocol.ecc.ECPublicKey;
|
||||
@@ -34,19 +35,17 @@ import org.signal.libsignal.zkgroup.backups.BackupLevel;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.attachments.AttachmentGenerator;
|
||||
import org.whispersystems.textsecuregcm.attachments.AttachmentUtil;
|
||||
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.configuration.BackupConfiguration;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecoveryClient;
|
||||
import org.whispersystems.textsecuregcm.attachments.AttachmentUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import org.whispersystems.textsecuregcm.util.ua.UnrecognizedUserAgentException;
|
||||
@@ -55,7 +54,6 @@ import org.whispersystems.textsecuregcm.util.ua.UserAgentUtil;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
public class BackupManager {
|
||||
|
||||
@@ -89,7 +87,7 @@ public class BackupManager {
|
||||
private final ExternalServiceCredentialsGenerator secureValueRecoveryBCredentialsGenerator;
|
||||
private final SecureValueRecoveryClient secureValueRecoveryBClient;
|
||||
private final Clock clock;
|
||||
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
|
||||
private final BackupConfiguration backupConfiguration;
|
||||
|
||||
public BackupManager(
|
||||
final BackupsDb backupsDb,
|
||||
@@ -101,7 +99,7 @@ public class BackupManager {
|
||||
final ExternalServiceCredentialsGenerator secureValueRecoveryBCredentialsGenerator,
|
||||
final SecureValueRecoveryClient secureValueRecoveryBClient,
|
||||
final Clock clock,
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
|
||||
final BackupConfiguration backupConfiguration) {
|
||||
this.backupsDb = backupsDb;
|
||||
this.serverSecretParams = serverSecretParams;
|
||||
this.rateLimiters = rateLimiters;
|
||||
@@ -111,7 +109,7 @@ public class BackupManager {
|
||||
this.secureValueRecoveryBClient = secureValueRecoveryBClient;
|
||||
this.clock = clock;
|
||||
this.secureValueRecoveryBCredentialsGenerator = secureValueRecoveryBCredentialsGenerator;
|
||||
this.dynamicConfigurationManager = dynamicConfigurationManager;
|
||||
this.backupConfiguration = backupConfiguration;
|
||||
}
|
||||
|
||||
|
||||
@@ -196,8 +194,7 @@ public class BackupManager {
|
||||
// update message backup TTL
|
||||
final StoredBackupAttributes storedBackupAttributes = backupsDb.ttlRefresh(backupUser).join();
|
||||
if (backupUser.credentialType() == BackupCredentialType.MEDIA) {
|
||||
final long maxTotalMediaSize =
|
||||
dynamicConfigurationManager.getConfiguration().getBackupConfiguration().maxTotalMediaSize();
|
||||
final long maxTotalMediaSize = backupConfiguration.maxTotalMediaSize();
|
||||
|
||||
// Report that the backup is out of quota if it is within 100MiB of the limit
|
||||
final boolean quotaExhausted = storedBackupAttributes.bytesUsed() >=
|
||||
@@ -258,8 +255,6 @@ public class BackupManager {
|
||||
*/
|
||||
public Flux<CopyResult> copyToBackup(final CopyQuota copyQuota) {
|
||||
final AuthenticatedBackupUser backupUser = copyQuota.backupUser();
|
||||
final DynamicBackupConfiguration backupConfiguration =
|
||||
dynamicConfigurationManager.getConfiguration().getBackupConfiguration();
|
||||
|
||||
return Flux.concat(
|
||||
|
||||
@@ -347,8 +342,6 @@ public class BackupManager {
|
||||
}
|
||||
final long totalBytesAdded = toCopy.stream().mapToLong(CopyParameters::destinationObjectSize).sum();
|
||||
|
||||
final DynamicBackupConfiguration backupConfiguration =
|
||||
dynamicConfigurationManager.getConfiguration().getBackupConfiguration();
|
||||
final Duration maxQuotaStaleness = backupConfiguration.maxQuotaStaleness();
|
||||
final long maxTotalMediaSize = backupConfiguration.maxTotalMediaSize();
|
||||
|
||||
@@ -491,8 +484,7 @@ public class BackupManager {
|
||||
public void deleteEntireBackup(final AuthenticatedBackupUser backupUser) throws BackupPermissionException {
|
||||
checkBackupLevel(backupUser, BackupLevel.FREE);
|
||||
|
||||
final int deletionConcurrency =
|
||||
dynamicConfigurationManager.getConfiguration().getBackupConfiguration().deletionConcurrency();
|
||||
final int deletionConcurrency = backupConfiguration.deletionConcurrency();
|
||||
|
||||
// Clients only include SVRB data with their messages backup-id
|
||||
if (backupUser.credentialType() == BackupCredentialType.MESSAGES) {
|
||||
@@ -523,8 +515,6 @@ public class BackupManager {
|
||||
if (storageDescriptors.stream().anyMatch(sd -> sd.cdn() != remoteStorageManager.cdnNumber())) {
|
||||
return Flux.error(new BackupInvalidArgumentException("unsupported media cdn provided"));
|
||||
}
|
||||
final DynamicBackupConfiguration backupConfiguration =
|
||||
dynamicConfigurationManager.getConfiguration().getBackupConfiguration();
|
||||
|
||||
return Flux.usingWhen(
|
||||
|
||||
|
||||
+3
-3
@@ -86,7 +86,7 @@ public class Cdn3RemoteStorageManager implements RemoteStorageManager {
|
||||
public CompletionStage<Void> copy(
|
||||
final int sourceCdn,
|
||||
final String sourceKey,
|
||||
final int expectedSourceLength,
|
||||
final long expectedSourceLength,
|
||||
final MediaEncryptionParameters encryptionParameters,
|
||||
final String destinationKey) {
|
||||
final String sourceScheme = this.sourceSchemes.get(sourceCdn);
|
||||
@@ -132,10 +132,10 @@ public class Cdn3RemoteStorageManager implements RemoteStorageManager {
|
||||
*/
|
||||
record Cdn3CopyRequest(
|
||||
String encryptionKey, String hmacKey,
|
||||
SourceDescriptor source, int expectedSourceLength,
|
||||
SourceDescriptor source, long expectedSourceLength,
|
||||
String dst) {
|
||||
|
||||
Cdn3CopyRequest(MediaEncryptionParameters parameters, SourceDescriptor source, int expectedSourceLength,
|
||||
Cdn3CopyRequest(MediaEncryptionParameters parameters, SourceDescriptor source, long expectedSourceLength,
|
||||
String dst) {
|
||||
this(Base64.getEncoder().encodeToString(parameters.aesEncryptionKey().getEncoded()),
|
||||
Base64.getEncoder().encodeToString(parameters.hmacSHA256Key().getEncoded()),
|
||||
|
||||
@@ -18,7 +18,7 @@ import com.google.common.annotations.VisibleForTesting;
|
||||
public record CopyParameters(
|
||||
int sourceCdn,
|
||||
String sourceKey,
|
||||
int sourceLength,
|
||||
long sourceLength,
|
||||
MediaEncryptionParameters encryptionParameters,
|
||||
byte[] destinationMediaId) {
|
||||
|
||||
@@ -35,16 +35,17 @@ public record CopyParameters(
|
||||
///
|
||||
/// @return the size, in bytes, of the ciphertext of a media object with the given `inputSize`
|
||||
@VisibleForTesting
|
||||
static long destinationObjectSize(final int inputSize) {
|
||||
static long destinationObjectSize(final long inputSize) {
|
||||
if (inputSize < 0) {
|
||||
throw new IllegalArgumentException("Size must be non-negative, but was " + inputSize);
|
||||
}
|
||||
|
||||
// AES-256 has 16-byte block size, and always adds a block if the plaintext is a multiple of the block size
|
||||
final long numBlocks = ((long) inputSize + 16) / 16;
|
||||
final long numBlocks = Math.addExact(inputSize, 16L) / 16;
|
||||
final long cipherTextLength = Math.multiplyExact(numBlocks, 16);
|
||||
|
||||
// 16-byte IV will be generated and prepended to the ciphertext
|
||||
// 16-byte IV will be generated and prepended to the ciphertext.
|
||||
// IV + AES-256 encrypted data + HmacSHA256
|
||||
return 16 + (numBlocks * 16) + 32;
|
||||
return Math.addExact(cipherTextLength, 16L + 32);
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -35,7 +35,7 @@ public interface RemoteStorageManager {
|
||||
CompletionStage<Void> copy(
|
||||
int sourceCdn,
|
||||
String sourceKey,
|
||||
int expectedSourceLength,
|
||||
long expectedSourceLength,
|
||||
MediaEncryptionParameters encryptionParameters,
|
||||
String dstKey);
|
||||
|
||||
|
||||
@@ -10,5 +10,8 @@ import java.util.Locale;
|
||||
import org.whispersystems.textsecuregcm.entities.Badge;
|
||||
|
||||
public interface BadgeTranslator {
|
||||
|
||||
Locale resolveLocale(List<Locale> acceptableLanguages);
|
||||
|
||||
Badge translate(List<Locale> acceptableLanguages, String badgeId);
|
||||
}
|
||||
+6
-18
@@ -7,7 +7,6 @@ package org.whispersystems.textsecuregcm.badges;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
@@ -31,7 +30,6 @@ public class ConfiguredProfileBadgeConverter implements ProfileBadgeConverter, B
|
||||
|
||||
private final Clock clock;
|
||||
private final Map<String, BadgeConfiguration> knownBadges;
|
||||
private final List<String> badgeIdsEnabledForAll;
|
||||
private final HeaderControlledResourceBundleLookup headerControlledResourceBundleLookup;
|
||||
|
||||
public ConfiguredProfileBadgeConverter(
|
||||
@@ -41,10 +39,14 @@ public class ConfiguredProfileBadgeConverter implements ProfileBadgeConverter, B
|
||||
this.clock = clock;
|
||||
this.knownBadges = badgesConfiguration.getBadges().stream()
|
||||
.collect(Collectors.toMap(BadgeConfiguration::getId, Function.identity()));
|
||||
this.badgeIdsEnabledForAll = badgesConfiguration.getBadgeIdsEnabledForAll();
|
||||
this.headerControlledResourceBundleLookup = headerControlledResourceBundleLookup;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Locale resolveLocale(final List<Locale> acceptableLanguages) {
|
||||
return headerControlledResourceBundleLookup.getResourceBundle(BASE_NAME, acceptableLanguages).getLocale();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Badge translate(final List<Locale> acceptableLanguages, final String badgeId) {
|
||||
final ResourceBundle resourceBundle = headerControlledResourceBundleLookup.getResourceBundle(BASE_NAME,
|
||||
@@ -68,7 +70,7 @@ public class ConfiguredProfileBadgeConverter implements ProfileBadgeConverter, B
|
||||
final List<Locale> acceptableLanguages,
|
||||
final List<AccountBadge> accountBadges,
|
||||
final boolean isSelf) {
|
||||
if (accountBadges.isEmpty() && badgeIdsEnabledForAll.isEmpty()) {
|
||||
if (accountBadges.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
@@ -94,20 +96,6 @@ public class ConfiguredProfileBadgeConverter implements ProfileBadgeConverter, B
|
||||
accountBadge.visible());
|
||||
})
|
||||
.collect(Collectors.toCollection(ArrayList::new));
|
||||
badges.addAll(badgeIdsEnabledForAll.stream().filter(knownBadges::containsKey).map(id -> {
|
||||
BadgeConfiguration configuration = knownBadges.get(id);
|
||||
return newBadge(
|
||||
isSelf,
|
||||
id,
|
||||
configuration.getCategory(),
|
||||
resourceBundle.getString(id + "_name"),
|
||||
resourceBundle.getString(id + "_description"),
|
||||
configuration.getSprites(),
|
||||
configuration.getSvg(),
|
||||
configuration.getSvgs(),
|
||||
now.plus(Duration.ofDays(1)),
|
||||
true);
|
||||
}).collect(Collectors.toList()));
|
||||
return badges;
|
||||
}
|
||||
|
||||
|
||||
+4
-4
@@ -3,7 +3,7 @@
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration.dynamic;
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import io.dropwizard.util.DataSize;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
@@ -17,14 +17,14 @@ import java.time.Duration;
|
||||
* @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(
|
||||
public record BackupConfiguration(
|
||||
@NotNull Integer deletionConcurrency,
|
||||
@NotNull Integer copyConcurrency,
|
||||
@NotNull Integer usageCheckpointCount,
|
||||
@NotNull Duration maxQuotaStaleness,
|
||||
@NotNull Long maxTotalMediaSize) {
|
||||
|
||||
public DynamicBackupConfiguration {
|
||||
public BackupConfiguration {
|
||||
if (deletionConcurrency == null) {
|
||||
deletionConcurrency = 10;
|
||||
}
|
||||
@@ -42,7 +42,7 @@ public record DynamicBackupConfiguration(
|
||||
}
|
||||
}
|
||||
|
||||
public DynamicBackupConfiguration() {
|
||||
public BackupConfiguration() {
|
||||
this(null, null, null, null, null);
|
||||
}
|
||||
}
|
||||
-9
@@ -21,16 +21,13 @@ import java.util.stream.Collectors;
|
||||
|
||||
public class BadgesConfiguration {
|
||||
private final List<BadgeConfiguration> badges;
|
||||
private final List<String> badgeIdsEnabledForAll;
|
||||
private final Map<Long, String> receiptLevels;
|
||||
|
||||
@JsonCreator
|
||||
public BadgesConfiguration(
|
||||
@JsonProperty("badges") @JsonSetter(nulls = Nulls.AS_EMPTY) final List<BadgeConfiguration> badges,
|
||||
@JsonProperty("badgeIdsEnabledForAll") @JsonSetter(nulls = Nulls.AS_EMPTY) final List<String> badgeIdsEnabledForAll,
|
||||
@JsonProperty("receiptLevels") @JsonSetter(nulls = Nulls.AS_EMPTY) final Map<Long, String> receiptLevels) {
|
||||
this.badges = Objects.requireNonNull(badges);
|
||||
this.badgeIdsEnabledForAll = Objects.requireNonNull(badgeIdsEnabledForAll);
|
||||
this.receiptLevels = Objects.requireNonNull(receiptLevels);
|
||||
}
|
||||
|
||||
@@ -40,12 +37,6 @@ public class BadgesConfiguration {
|
||||
return badges;
|
||||
}
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
public List<String> getBadgeIdsEnabledForAll() {
|
||||
return badgeIdsEnabledForAll;
|
||||
}
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
public Map<Long, String> getReceiptLevels() {
|
||||
|
||||
+18
@@ -55,6 +55,7 @@ public class DynamoDbTables {
|
||||
private final Table clientReleases;
|
||||
private final Table deletedAccounts;
|
||||
private final Table deletedAccountsLock;
|
||||
private final TableWithExpiration donationPermits;
|
||||
private final IssuedReceiptsTableConfiguration issuedReceipts;
|
||||
private final Table ecKeys;
|
||||
private final Table ecSignedPreKeys;
|
||||
@@ -63,6 +64,7 @@ public class DynamoDbTables {
|
||||
private final TableWithExpiration messages;
|
||||
private final TableWithExpiration onetimeDonations;
|
||||
private final Table phoneNumberIdentifiers;
|
||||
private final Table profileAvatars;
|
||||
private final Table profiles;
|
||||
private final Table profilesV2;
|
||||
private final Table pushChallenge;
|
||||
@@ -84,6 +86,7 @@ public class DynamoDbTables {
|
||||
@JsonProperty("clientReleases") final Table clientReleases,
|
||||
@JsonProperty("deletedAccounts") final Table deletedAccounts,
|
||||
@JsonProperty("deletedAccountsLock") final Table deletedAccountsLock,
|
||||
@JsonProperty("donationPermits") final TableWithExpiration donationPermits,
|
||||
@JsonProperty("issuedReceipts") final IssuedReceiptsTableConfiguration issuedReceipts,
|
||||
@JsonProperty("ecKeys") final Table ecKeys,
|
||||
@JsonProperty("ecSignedPreKeys") final Table ecSignedPreKeys,
|
||||
@@ -92,6 +95,7 @@ public class DynamoDbTables {
|
||||
@JsonProperty("messages") final TableWithExpiration messages,
|
||||
@JsonProperty("onetimeDonations") final TableWithExpiration onetimeDonations,
|
||||
@JsonProperty("phoneNumberIdentifiers") final Table phoneNumberIdentifiers,
|
||||
@JsonProperty("profileAvatars") final Table profileAvatars,
|
||||
@JsonProperty("profiles") final Table profiles,
|
||||
@JsonProperty("profilesV2") final Table profilesV2,
|
||||
@JsonProperty("pushChallenge") final Table pushChallenge,
|
||||
@@ -112,6 +116,7 @@ public class DynamoDbTables {
|
||||
this.clientReleases = clientReleases;
|
||||
this.deletedAccounts = deletedAccounts;
|
||||
this.deletedAccountsLock = deletedAccountsLock;
|
||||
this.donationPermits = donationPermits;
|
||||
this.issuedReceipts = issuedReceipts;
|
||||
this.ecKeys = ecKeys;
|
||||
this.ecSignedPreKeys = ecSignedPreKeys;
|
||||
@@ -120,6 +125,7 @@ public class DynamoDbTables {
|
||||
this.messages = messages;
|
||||
this.onetimeDonations = onetimeDonations;
|
||||
this.phoneNumberIdentifiers = phoneNumberIdentifiers;
|
||||
this.profileAvatars = profileAvatars;
|
||||
this.profiles = profiles;
|
||||
this.profilesV2 = profilesV2;
|
||||
this.pushChallenge = pushChallenge;
|
||||
@@ -181,6 +187,12 @@ public class DynamoDbTables {
|
||||
return deletedAccountsLock;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
public TableWithExpiration getDonationPermits() {
|
||||
return donationPermits;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
public IssuedReceiptsTableConfiguration getIssuedReceipts() {
|
||||
@@ -229,6 +241,12 @@ public class DynamoDbTables {
|
||||
return phoneNumberIdentifiers;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
public Table getProfileAvatars() {
|
||||
return profileAvatars;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
public Table getProfilesV1() {
|
||||
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import com.apple.foundationdb.Database;
|
||||
import com.apple.foundationdb.FDB;
|
||||
import com.fasterxml.jackson.annotation.JsonTypeName;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import java.io.File;
|
||||
import java.io.FileWriter;
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.time.Duration;
|
||||
|
||||
@JsonTypeName("default")
|
||||
public record FoundationDbClusterConfiguration(@NotBlank String clusterFileUrl) implements FoundationDbDatabaseFactory {
|
||||
|
||||
@Override
|
||||
public Database build(final FDB fdb) throws IOException {
|
||||
final URI clusterFileUri = URI.create(clusterFileUrl());
|
||||
|
||||
final File clusterFile = switch (clusterFileUri.getScheme()) {
|
||||
case "file" -> new File(clusterFileUri);
|
||||
|
||||
case "http", "https" -> {
|
||||
try (final HttpClient clusterFileClient = HttpClient.newBuilder()
|
||||
.version(HttpClient.Version.HTTP_1_1)
|
||||
.connectTimeout(Duration.ofSeconds(10))
|
||||
.build()) {
|
||||
|
||||
final HttpResponse<String> response = clusterFileClient.send(HttpRequest.newBuilder()
|
||||
.uri(URI.create(clusterFileUrl()))
|
||||
.timeout(Duration.ofSeconds(10))
|
||||
.GET()
|
||||
.build(), HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
if (response.statusCode() != 200) {
|
||||
throw new IOException("Could not load cluster file (status " + response.statusCode() + ")");
|
||||
}
|
||||
|
||||
final File tempClusterFile = File.createTempFile("fdb.cluster-", "");
|
||||
tempClusterFile.deleteOnExit();
|
||||
|
||||
try (final FileWriter fileWriter = new FileWriter(tempClusterFile)) {
|
||||
fileWriter.write(response.body());
|
||||
}
|
||||
|
||||
yield tempClusterFile;
|
||||
} catch (final InterruptedException e) {
|
||||
throw new IOException("Interrupted while waiting for cluster file response", e);
|
||||
}
|
||||
}
|
||||
|
||||
default -> throw new IllegalArgumentException("Unrecognized cluster file URI scheme: " + clusterFileUri.getScheme());
|
||||
};
|
||||
|
||||
return fdb.open(clusterFile.getAbsolutePath());
|
||||
}
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import com.apple.foundationdb.Database;
|
||||
import com.apple.foundationdb.FDB;
|
||||
import com.fasterxml.jackson.annotation.JsonTypeInfo;
|
||||
import io.dropwizard.jackson.Discoverable;
|
||||
import java.io.IOException;
|
||||
|
||||
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type", defaultImpl = FoundationDbClusterConfiguration.class)
|
||||
public interface FoundationDbDatabaseFactory extends Discoverable {
|
||||
|
||||
Database build(final FDB fdb) throws IOException;
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.AssertTrue;
|
||||
import jakarta.validation.constraints.Max;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import jakarta.validation.constraints.PositiveOrZero;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import org.whispersystems.textsecuregcm.configuration.secrets.SecretBytes;
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStore;
|
||||
|
||||
public record FoundationDbMessagesConfiguration(@NotEmpty Map<String, @Valid FoundationDbDatabaseFactory> clusters,
|
||||
@NotEmpty Map<@PositiveOrZero @Max(FoundationDbMessageStore.MAX_EPOCHS - 1) Integer, @Size(min = 1, max = FoundationDbMessageStore.MAX_SHARDS - 1) List<String>> epochs,
|
||||
@PositiveOrZero @Max(FoundationDbMessageStore.MAX_EPOCHS - 1) int activeEpoch,
|
||||
@NotEmpty Map<@PositiveOrZero @Max(63) Integer, SecretBytes> versionstampCipherKeys,
|
||||
@PositiveOrZero @Max(63) int currentVersionstampCipherKey,
|
||||
@PositiveOrZero @Max(1_000_000) long maxWatchesPerClient) {
|
||||
|
||||
public static final long DEFAULT_MAX_WATCHES_PER_CLIENT = 10_000;
|
||||
|
||||
@AssertTrue
|
||||
boolean isEveryEpochClusterConfigured() {
|
||||
for (final List<String> clustersInEpoch : epochs().values()) {
|
||||
for (final String cluster : clustersInEpoch) {
|
||||
if (!clusters.containsKey(cluster)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@AssertTrue
|
||||
boolean isEveryEpochFreeOfDuplicates() {
|
||||
for (final List<String> clustersInEpoch : epochs().values()) {
|
||||
if (new HashSet<>(clustersInEpoch).size() != clustersInEpoch.size()) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@AssertTrue
|
||||
boolean isActiveEpochConfigured() {
|
||||
return epochs().containsKey(activeEpoch());
|
||||
}
|
||||
|
||||
@AssertTrue
|
||||
boolean isCurrentVersionstampCipherKeyConfigured() {
|
||||
return versionstampCipherKeys().containsKey(currentVersionstampCipherKey());
|
||||
}
|
||||
}
|
||||
+1
-2
@@ -15,6 +15,5 @@ import java.util.concurrent.ScheduledExecutorService;
|
||||
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type", defaultImpl = RegistrationServiceConfiguration.class)
|
||||
public interface RegistrationServiceClientFactory extends Discoverable {
|
||||
|
||||
RegistrationServiceClient build(Environment environment, Executor callbackExecutor,
|
||||
ScheduledExecutorService identityRefreshExecutor);
|
||||
RegistrationServiceClient build(Environment environment, ScheduledExecutorService identityRefreshExecutor);
|
||||
}
|
||||
+3
-4
@@ -5,7 +5,6 @@ import io.dropwizard.core.setup.Environment;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import java.io.IOException;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import org.whispersystems.textsecuregcm.configuration.secrets.SecretBytes;
|
||||
import org.whispersystems.textsecuregcm.registration.IdentityTokenCallCredentials;
|
||||
@@ -21,16 +20,16 @@ public record RegistrationServiceConfiguration(@NotBlank String host,
|
||||
RegistrationServiceClientFactory {
|
||||
|
||||
@Override
|
||||
public RegistrationServiceClient build(final Environment environment, final Executor callbackExecutor,
|
||||
public RegistrationServiceClient build(final Environment environment,
|
||||
final ScheduledExecutorService identityRefreshExecutor) {
|
||||
|
||||
try {
|
||||
final IdentityTokenCallCredentials callCredentials = IdentityTokenCallCredentials.fromCredentialConfig(
|
||||
credentialConfigurationJson, identityTokenAudience, identityRefreshExecutor);
|
||||
|
||||
environment.lifecycle().manage(callCredentials);
|
||||
|
||||
return new RegistrationServiceClient(host, port, callCredentials, registrationCaCertificate, collationKeySalt.value(),
|
||||
identityRefreshExecutor);
|
||||
return new RegistrationServiceClient(host, port, callCredentials, registrationCaCertificate, collationKeySalt.value());
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
+9
-8
@@ -7,6 +7,7 @@ package org.whispersystems.textsecuregcm.configuration.dynamic;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import jakarta.validation.Valid;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
@@ -68,10 +69,6 @@ public class DynamicConfiguration {
|
||||
@Valid
|
||||
DynamicRestDeprecationConfiguration restDeprecation = new DynamicRestDeprecationConfiguration(Map.of());
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
private DynamicBackupConfiguration backup = new DynamicBackupConfiguration();
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
private DynamicCarrierDataLookupConfiguration carrierDataLookup = new DynamicCarrierDataLookupConfiguration();
|
||||
@@ -80,6 +77,10 @@ public class DynamicConfiguration {
|
||||
@Valid
|
||||
private DynamicGrpcAllowListConfiguration grpcAllowList = new DynamicGrpcAllowListConfiguration();
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
private DynamicOmnibusConfiguration omnibus = new DynamicOmnibusConfiguration(BigDecimal.ZERO);
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
private DynamicTurnConfiguration turn = new DynamicTurnConfiguration();
|
||||
@@ -138,10 +139,6 @@ public class DynamicConfiguration {
|
||||
return restDeprecation;
|
||||
}
|
||||
|
||||
public DynamicBackupConfiguration getBackupConfiguration() {
|
||||
return backup;
|
||||
}
|
||||
|
||||
public DynamicCarrierDataLookupConfiguration getCarrierDataLookupConfiguration() {
|
||||
return carrierDataLookup;
|
||||
}
|
||||
@@ -150,6 +147,10 @@ public class DynamicConfiguration {
|
||||
return grpcAllowList;
|
||||
}
|
||||
|
||||
public DynamicOmnibusConfiguration getOmnibus() {
|
||||
return omnibus;
|
||||
}
|
||||
|
||||
public DynamicTurnConfiguration getTurnConfiguration() {
|
||||
return turn;
|
||||
}
|
||||
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.configuration.dynamic;
|
||||
|
||||
import jakarta.validation.constraints.DecimalMax;
|
||||
import jakarta.validation.constraints.DecimalMin;
|
||||
import java.math.BigDecimal;
|
||||
|
||||
/// @param rejectConnectionRatio The proportion of connection attempts that should be immediately closed with a GOAWAY
|
||||
public record DynamicOmnibusConfiguration(@DecimalMin("0.0") @DecimalMax("1.0") BigDecimal rejectConnectionRatio) {
|
||||
}
|
||||
+21
-3
@@ -5,16 +5,21 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import com.google.common.net.HttpHeaders;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.micrometer.core.instrument.DistributionSummary;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.headers.Header;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.Positive;
|
||||
import jakarta.ws.rs.ClientErrorException;
|
||||
import jakarta.ws.rs.GET;
|
||||
import jakarta.ws.rs.HeaderParam;
|
||||
import jakarta.ws.rs.Path;
|
||||
import jakarta.ws.rs.Produces;
|
||||
import jakarta.ws.rs.QueryParam;
|
||||
@@ -24,6 +29,7 @@ import java.security.SecureRandom;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import javax.annotation.Nonnull;
|
||||
import javax.annotation.Nullable;
|
||||
import org.whispersystems.textsecuregcm.attachments.AttachmentGenerator;
|
||||
import org.whispersystems.textsecuregcm.attachments.AttachmentUtil;
|
||||
import org.whispersystems.textsecuregcm.attachments.GcsAttachmentGenerator;
|
||||
@@ -33,6 +39,8 @@ import org.whispersystems.textsecuregcm.entities.AttachmentDescriptorV3;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
|
||||
|
||||
/**
|
||||
@@ -40,7 +48,7 @@ import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
* (message attachments) to a remote storage location. The location may be selected by the server at runtime.
|
||||
*/
|
||||
@Path("/v4/attachments")
|
||||
@Tag(name = "Attachments")
|
||||
@io.swagger.v3.oas.annotations.tags.Tag(name = "Attachments")
|
||||
public class AttachmentControllerV4 {
|
||||
|
||||
private final ExperimentEnrollmentManager experimentEnrollmentManager;
|
||||
@@ -50,6 +58,9 @@ public class AttachmentControllerV4 {
|
||||
|
||||
private final Map<Integer, AttachmentGenerator> attachmentGenerators;
|
||||
|
||||
private static final String ATTACHMENT_SIZE_NAME =
|
||||
MetricsUtil.name(AttachmentControllerV4.class, "attachmentSize");
|
||||
|
||||
@Nonnull
|
||||
private final SecureRandom secureRandom;
|
||||
|
||||
@@ -91,7 +102,8 @@ public class AttachmentControllerV4 {
|
||||
public AttachmentDescriptorV3 getAttachmentUploadForm(
|
||||
@Auth AuthenticatedDevice auth,
|
||||
@Parameter(description = "The size of the attachment to upload in bytes")
|
||||
@QueryParam("uploadLength") final @Valid Optional<@Positive Long> maybeUploadLength)
|
||||
@QueryParam("uploadLength") final @Valid Optional<@Positive Long> maybeUploadLength,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) @Nullable final String userAgent)
|
||||
throws RateLimitExceededException {
|
||||
|
||||
final long uploadLength = maybeUploadLength.orElse(maxUploadLength);
|
||||
@@ -111,6 +123,12 @@ public class AttachmentControllerV4 {
|
||||
}
|
||||
}
|
||||
|
||||
DistributionSummary.builder(ATTACHMENT_SIZE_NAME)
|
||||
.tags(Tags.of(UserAgentTagUtil.getPlatformTag(userAgent),
|
||||
Tag.of("uploadLengthSupplied", Boolean.toString(maybeUploadLength.isPresent()))))
|
||||
.register(Metrics.globalRegistry)
|
||||
.record(uploadLength);
|
||||
|
||||
final String key = AttachmentUtil.generateAttachmentKey(secureRandom);
|
||||
final boolean useCdn3 = this.experimentEnrollmentManager.isEnrolled(auth.accountIdentifier(), AttachmentUtil.CDN3_EXPERIMENT_NAME);
|
||||
int cdn = useCdn3 ? 3 : 2;
|
||||
|
||||
+49
-7
@@ -11,6 +11,7 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.ws.rs.BadRequestException;
|
||||
import jakarta.ws.rs.Consumes;
|
||||
import jakarta.ws.rs.POST;
|
||||
import jakarta.ws.rs.Path;
|
||||
@@ -21,18 +22,23 @@ import jakarta.ws.rs.core.Response.Status;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.util.Objects;
|
||||
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.donation.DonationPermitRequest;
|
||||
import org.signal.libsignal.zkgroup.donation.DonationPermitResponse;
|
||||
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialPresentation;
|
||||
import org.signal.libsignal.zkgroup.receipts.ReceiptSerial;
|
||||
import org.signal.libsignal.zkgroup.receipts.ServerZkReceiptOperations;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.configuration.BadgesConfiguration;
|
||||
import org.whispersystems.textsecuregcm.entities.CreateDonationPermitResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.CreateDonationPermitsRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.RedeemReceiptRequest;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountBadge;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.DonationPermitsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.RedeemedReceiptsManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.ReceiptCredentialPresentationFactory;
|
||||
|
||||
@@ -46,20 +52,26 @@ public class DonationController {
|
||||
private final AccountsManager accountsManager;
|
||||
private final BadgesConfiguration badgesConfiguration;
|
||||
private final ReceiptCredentialPresentationFactory receiptCredentialPresentationFactory;
|
||||
private final DonationPermitsManager donationPermitsManager;
|
||||
private final RateLimiters rateLimiters;
|
||||
|
||||
public DonationController(
|
||||
@Nonnull final Clock clock,
|
||||
@Nonnull final ServerZkReceiptOperations serverZkReceiptOperations,
|
||||
@Nonnull final RedeemedReceiptsManager redeemedReceiptsManager,
|
||||
@Nonnull final AccountsManager accountsManager,
|
||||
@Nonnull final BadgesConfiguration badgesConfiguration,
|
||||
@Nonnull final ReceiptCredentialPresentationFactory receiptCredentialPresentationFactory) {
|
||||
final Clock clock,
|
||||
final ServerZkReceiptOperations serverZkReceiptOperations,
|
||||
final RedeemedReceiptsManager redeemedReceiptsManager,
|
||||
final AccountsManager accountsManager,
|
||||
final BadgesConfiguration badgesConfiguration,
|
||||
final ReceiptCredentialPresentationFactory receiptCredentialPresentationFactory,
|
||||
final DonationPermitsManager donationPermitsManager,
|
||||
final RateLimiters rateLimiters) {
|
||||
this.clock = Objects.requireNonNull(clock);
|
||||
this.serverZkReceiptOperations = Objects.requireNonNull(serverZkReceiptOperations);
|
||||
this.redeemedReceiptsManager = Objects.requireNonNull(redeemedReceiptsManager);
|
||||
this.accountsManager = Objects.requireNonNull(accountsManager);
|
||||
this.badgesConfiguration = Objects.requireNonNull(badgesConfiguration);
|
||||
this.receiptCredentialPresentationFactory = Objects.requireNonNull(receiptCredentialPresentationFactory);
|
||||
this.donationPermitsManager = Objects.requireNonNull(donationPermitsManager);
|
||||
this.rateLimiters = Objects.requireNonNull(rateLimiters);
|
||||
}
|
||||
|
||||
@POST
|
||||
@@ -131,4 +143,34 @@ public class DonationController {
|
||||
return Response.ok().build();
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/permit")
|
||||
@Produces({MediaType.APPLICATION_JSON})
|
||||
@Operation(
|
||||
summary = "Generate permits for anonymous donation endpoints",
|
||||
description = """
|
||||
Generate a set of anonymous, single-use, permits for use with /v1/subscription endpoints.
|
||||
""")
|
||||
@ApiResponse(responseCode = "200", description = "`JSON` with generated credentials", useReturnTypeSchema = true)
|
||||
@ApiResponse(responseCode = "400", description = "Invalid credential request")
|
||||
@ApiResponse(responseCode = "401", description = "Account authentication check failed")
|
||||
@ApiResponse(responseCode = "422", description = "Invalid request format")
|
||||
@ApiResponse(responseCode = "429", description = "Rate-limited; reduce requested permit count and/or try again after the prescribed delay")
|
||||
public CreateDonationPermitResponse createPermits(@Auth final AuthenticatedDevice auth,
|
||||
@NotNull @Valid final CreateDonationPermitsRequest request) throws RateLimitExceededException {
|
||||
|
||||
final DonationPermitRequest permitRequest;
|
||||
try {
|
||||
permitRequest = new DonationPermitRequest(request.permitRequest());
|
||||
} catch (InvalidInputException e) {
|
||||
throw new BadRequestException();
|
||||
}
|
||||
|
||||
rateLimiters.getCreateDonationPermitLimiter().validate(auth.accountIdentifier(), permitRequest.getPermitCount());
|
||||
|
||||
final DonationPermitResponse permitResponse = donationPermitsManager.issue(permitRequest);
|
||||
|
||||
return new CreateDonationPermitResponse(permitResponse.serialize());
|
||||
}
|
||||
|
||||
}
|
||||
+31
-12
@@ -33,6 +33,8 @@ import org.glassfish.jersey.server.ManagedAsync;
|
||||
import org.signal.keytransparency.client.AciMonitorRequest;
|
||||
import org.signal.keytransparency.client.E164MonitorRequest;
|
||||
import org.signal.keytransparency.client.E164SearchRequest;
|
||||
import org.signal.keytransparency.client.MonitorResponseV2;
|
||||
import org.signal.keytransparency.client.SearchResponseV2;
|
||||
import org.signal.keytransparency.client.UsernameHashMonitorRequest;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
@@ -101,15 +103,23 @@ public class KeyTransparencyController {
|
||||
.build()
|
||||
));
|
||||
|
||||
return new KeyTransparencySearchResponse(
|
||||
keyTransparencyServiceClient.search(
|
||||
ByteString.copyFrom(request.aci().toCompactByteArray()),
|
||||
ByteString.copyFrom(request.aciIdentityKey().serialize()),
|
||||
request.usernameHash().map(ByteString::copyFrom),
|
||||
maybeE164SearchRequest,
|
||||
request.lastTreeHeadSize(),
|
||||
request.distinguishedTreeHeadSize())
|
||||
.toByteArray());
|
||||
final SearchResponseV2 searchResponse = keyTransparencyServiceClient.search(
|
||||
ByteString.copyFrom(request.aci().toCompactByteArray()),
|
||||
ByteString.copyFrom(request.aciIdentityKey().serialize()),
|
||||
request.usernameHash().map(ByteString::copyFrom),
|
||||
maybeE164SearchRequest,
|
||||
request.lastTreeHeadSize(),
|
||||
request.distinguishedTreeHeadSize());
|
||||
|
||||
if (searchResponse.hasPermissionDenied()) {
|
||||
throw new StatusRuntimeException(Status.PERMISSION_DENIED);
|
||||
}
|
||||
|
||||
if (!searchResponse.hasSearchResponse()) {
|
||||
throw new StatusRuntimeException(Status.UNAVAILABLE.withDescription("Missing search response"));
|
||||
}
|
||||
|
||||
return new KeyTransparencySearchResponse(searchResponse.getSearchResponse().toByteArray());
|
||||
} catch (final StatusRuntimeException exception) {
|
||||
handleKeyTransparencyServiceError(exception);
|
||||
}
|
||||
@@ -163,13 +173,22 @@ public class KeyTransparencyController {
|
||||
.setCommitmentIndex(ByteString.copyFrom(e164.commitmentIndex()))
|
||||
.build());
|
||||
|
||||
return new KeyTransparencyMonitorResponse(keyTransparencyServiceClient.monitor(
|
||||
final MonitorResponseV2 monitorResponse = keyTransparencyServiceClient.monitor(
|
||||
aciMonitorRequest,
|
||||
usernameHashMonitorRequest,
|
||||
e164MonitorRequest,
|
||||
request.lastNonDistinguishedTreeHeadSize(),
|
||||
request.lastDistinguishedTreeHeadSize())
|
||||
.toByteArray());
|
||||
request.lastDistinguishedTreeHeadSize());
|
||||
|
||||
if (monitorResponse.hasPermissionDenied()) {
|
||||
throw new StatusRuntimeException(Status.PERMISSION_DENIED);
|
||||
}
|
||||
|
||||
if (!monitorResponse.hasMonitorResponse()) {
|
||||
throw new StatusRuntimeException(Status.UNAVAILABLE.withDescription("Missing monitor response"));
|
||||
}
|
||||
|
||||
return new KeyTransparencyMonitorResponse(monitorResponse.getMonitorResponse().toByteArray());
|
||||
} catch (final StatusRuntimeException exception) {
|
||||
handleKeyTransparencyServiceError(exception);
|
||||
}
|
||||
|
||||
+162
-186
@@ -4,13 +4,17 @@
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil.getClientPlatform;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import com.google.common.net.HttpHeaders;
|
||||
import com.stripe.model.PaymentIntent;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.StringToClassMapItem;
|
||||
import io.swagger.v3.oas.annotations.media.Content;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
@@ -31,19 +35,18 @@ import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import jakarta.ws.rs.core.Context;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import java.io.IOException;
|
||||
import java.math.BigDecimal;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import javax.annotation.Nonnull;
|
||||
import javax.annotation.Nullable;
|
||||
import org.glassfish.jersey.server.ManagedAsync;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.VerificationFailedException;
|
||||
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialRequest;
|
||||
@@ -52,10 +55,14 @@ import org.signal.libsignal.zkgroup.receipts.ServerZkReceiptOperations;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.DonationPermitHeader;
|
||||
import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration;
|
||||
import org.whispersystems.textsecuregcm.grpc.OneTimeDonationUtil;
|
||||
import org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimitedByIp;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.DonationPermitsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.IssuedReceiptsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.OneTimeDonationsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.WriteConflictException;
|
||||
@@ -68,13 +75,10 @@ import org.whispersystems.textsecuregcm.subscriptions.PaymentMethod;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentStatus;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.StripeManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionCurrencyUtil;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidAmountException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorException;
|
||||
import org.whispersystems.textsecuregcm.util.ExactlySize;
|
||||
import org.whispersystems.textsecuregcm.util.HeaderUtils;
|
||||
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
|
||||
import org.whispersystems.textsecuregcm.util.ua.UnrecognizedUserAgentException;
|
||||
import org.whispersystems.textsecuregcm.util.ua.UserAgentUtil;
|
||||
|
||||
|
||||
/**
|
||||
* Endpoints for making one-time donation payments (boost and gift)
|
||||
@@ -89,8 +93,6 @@ public class OneTimeDonationController {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(OneTimeDonationController.class);
|
||||
|
||||
private static final String EURO_CURRENCY_CODE = "EUR";
|
||||
|
||||
private final Clock clock;
|
||||
private final OneTimeDonationConfiguration oneTimeDonationConfiguration;
|
||||
private final StripeManager stripeManager;
|
||||
@@ -99,16 +101,18 @@ public class OneTimeDonationController {
|
||||
private final ServerZkReceiptOperations zkReceiptOperations;
|
||||
private final IssuedReceiptsManager issuedReceiptsManager;
|
||||
private final OneTimeDonationsManager oneTimeDonationsManager;
|
||||
private final DonationPermitsManager donationPermitsManager;
|
||||
|
||||
public OneTimeDonationController(
|
||||
@Nonnull Clock clock,
|
||||
@Nonnull OneTimeDonationConfiguration oneTimeDonationConfiguration,
|
||||
@Nonnull StripeManager stripeManager,
|
||||
@Nonnull BraintreeManager braintreeManager,
|
||||
@Nonnull PayPalDonationsTranslator payPalDonationsTranslator,
|
||||
@Nonnull ServerZkReceiptOperations zkReceiptOperations,
|
||||
@Nonnull IssuedReceiptsManager issuedReceiptsManager,
|
||||
@Nonnull OneTimeDonationsManager oneTimeDonationsManager) {
|
||||
final Clock clock,
|
||||
final OneTimeDonationConfiguration oneTimeDonationConfiguration,
|
||||
final StripeManager stripeManager,
|
||||
final BraintreeManager braintreeManager,
|
||||
final PayPalDonationsTranslator payPalDonationsTranslator,
|
||||
final ServerZkReceiptOperations zkReceiptOperations,
|
||||
final IssuedReceiptsManager issuedReceiptsManager,
|
||||
final OneTimeDonationsManager oneTimeDonationsManager,
|
||||
final DonationPermitsManager donationPermitsManager) {
|
||||
this.clock = Objects.requireNonNull(clock);
|
||||
this.oneTimeDonationConfiguration = Objects.requireNonNull(oneTimeDonationConfiguration);
|
||||
this.stripeManager = Objects.requireNonNull(stripeManager);
|
||||
@@ -117,6 +121,7 @@ public class OneTimeDonationController {
|
||||
this.zkReceiptOperations = Objects.requireNonNull(zkReceiptOperations);
|
||||
this.issuedReceiptsManager = Objects.requireNonNull(issuedReceiptsManager);
|
||||
this.oneTimeDonationsManager = Objects.requireNonNull(oneTimeDonationsManager);
|
||||
this.donationPermitsManager = Objects.requireNonNull(donationPermitsManager);
|
||||
}
|
||||
|
||||
public static class CreateBoostRequest {
|
||||
@@ -147,10 +152,10 @@ public class OneTimeDonationController {
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Operation(summary = "Create a Stripe payment intent", description = """
|
||||
Create a Stripe PaymentIntent and return a client secret that can be used to complete the payment.
|
||||
|
||||
Once the payment is complete, the paymentIntentId can be used at /v1/subscriptions/receipt_credentials
|
||||
""")
|
||||
Create a Stripe PaymentIntent and return a client secret that can be used to complete the payment.
|
||||
|
||||
Once the payment is complete, the paymentIntentId can be used at /v1/subscriptions/receipt_credentials
|
||||
""")
|
||||
@ApiResponse(responseCode = "200", description = "Payment Intent created", content = @Content(schema = @Schema(implementation = CreateBoostResponse.class)))
|
||||
@ApiResponse(responseCode = "403", description = "The request was made on an authenticated channel")
|
||||
@ApiResponse(responseCode = "400", description = """
|
||||
@@ -164,65 +169,72 @@ public class OneTimeDonationController {
|
||||
properties = {
|
||||
@StringToClassMapItem(key = "error", value = String.class)
|
||||
})))
|
||||
@ApiResponse(responseCode = "401", description = "Donation permit was invalid or already spent")
|
||||
@RateLimitedByIp(RateLimiters.For.ONE_TIME_DONATION)
|
||||
public CompletableFuture<Response> createBoostPaymentIntent(
|
||||
@Auth Optional<AuthenticatedDevice> authenticatedAccount,
|
||||
@NotNull @Valid CreateBoostRequest request,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent) {
|
||||
@ManagedAsync
|
||||
public CreateBoostResponse createBoostPaymentIntent(
|
||||
@Auth final Optional<AuthenticatedDevice> authenticatedAccount,
|
||||
|
||||
@Parameter(description = "A base64-encoded donation permit retrieved from POST /v1/donation/permit")
|
||||
@HeaderParam(HeaderUtils.DONATION_PERMIT) final Optional<DonationPermitHeader> donationPermitHeader,
|
||||
|
||||
@NotNull @Valid final CreateBoostRequest request,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent) throws SubscriptionInvalidAmountException {
|
||||
|
||||
if (authenticatedAccount.isPresent()) {
|
||||
throw new ForbiddenException("must not use authenticated connection for one-time donation operations");
|
||||
}
|
||||
|
||||
return CompletableFuture.runAsync(() ->
|
||||
validateRequestCurrencyAmount(request, BigDecimal.valueOf(request.amount), stripeManager))
|
||||
.thenCompose(_ -> stripeManager.createPaymentIntent(request.currency, request.amount, request.level,
|
||||
getClientPlatform(userAgent)))
|
||||
.thenApply(paymentIntent -> Response.ok(new CreateBoostResponse(paymentIntent.getClientSecret())).build());
|
||||
SubscriptionsUtil.recordDonationPermitPresent(donationPermitHeader.isPresent(), "boostCreate", userAgent);
|
||||
final boolean spendSuccessful = donationPermitHeader.map(
|
||||
permitHeader -> {
|
||||
try {
|
||||
return SubscriptionsUtil.verifyAndSpendDonationPermit(permitHeader.permit(), donationPermitsManager, clock);
|
||||
} catch (final VerificationFailedException e) {
|
||||
return false;
|
||||
}
|
||||
})
|
||||
.orElse(true);
|
||||
if (!spendSuccessful) {
|
||||
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
|
||||
}
|
||||
|
||||
validateRequestCurrencyAmount(request, BigDecimal.valueOf(request.amount), stripeManager);
|
||||
final PaymentIntent paymentIntent = stripeManager.createPaymentIntent(request.currency, request.amount,
|
||||
request.level,
|
||||
getClientPlatform(userAgent));
|
||||
return new CreateBoostResponse(paymentIntent.getClientSecret());
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates that the request level is valid, the currency is supported by the {@code manager} and {@code request.paymentMethod},
|
||||
* and that the amount meets minimum and maximum constraints.
|
||||
* Validates that the request level is valid, the currency is supported by the {@code manager} and
|
||||
* {@code request.paymentMethod}, and that the amount meets minimum and maximum constraints.
|
||||
*
|
||||
* @throws BadRequestException indicates validation failed. Inspect {@code response.error} for details
|
||||
*/
|
||||
private void validateRequestCurrencyAmount(final CreateBoostRequest request, final BigDecimal amount,
|
||||
final CustomerAwareSubscriptionPaymentProcessor manager) {
|
||||
|
||||
if (!(request.level == oneTimeDonationConfiguration.gift().level()
|
||||
|| request.level == oneTimeDonationConfiguration.boost().level())) {
|
||||
final Map<String, String> errorBody = switch (OneTimeDonationUtil.validateOneTimeDonationRequest(request.currency,
|
||||
amount, request.level, request.paymentMethod, oneTimeDonationConfiguration, manager)) {
|
||||
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.UnsupportedLevel _ ->
|
||||
Map.of("error", "invalid_level");
|
||||
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.UnsupportedCurrency _ ->
|
||||
Map.of("error", "unsupported_currency");
|
||||
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.AmountBelowMinimum(final BigDecimal min) ->
|
||||
Map.of("error", "amount_below_currency_minimum",
|
||||
"minimum", min.toString());
|
||||
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.AmountAboveSepaLimit(final BigDecimal max) ->
|
||||
Map.of("error", "amount_above_sepa_limit",
|
||||
"maximum", max.toString());
|
||||
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.Success _ -> Collections.emptyMap();
|
||||
};
|
||||
|
||||
if (!errorBody.isEmpty()) {
|
||||
throw new BadRequestException(
|
||||
Response.status(Response.Status.BAD_REQUEST).entity(Map.of("error", "invalid_level")).build());
|
||||
Response.status(Response.Status.BAD_REQUEST).entity(errorBody).build());
|
||||
}
|
||||
|
||||
if (!manager.getSupportedCurrenciesForPaymentMethod(request.paymentMethod)
|
||||
.contains(request.currency.toLowerCase(Locale.ROOT))) {
|
||||
throw new BadRequestException(Response.status(Response.Status.BAD_REQUEST)
|
||||
.entity(Map.of("error", "unsupported_currency")).build());
|
||||
}
|
||||
|
||||
final BigDecimal minCurrencyAmountMajorUnits = oneTimeDonationConfiguration.currencies()
|
||||
.get(request.currency.toLowerCase(Locale.ROOT)).minimum();
|
||||
final BigDecimal minCurrencyAmountMinorUnits = SubscriptionCurrencyUtil.convertConfiguredAmountToApiAmount(
|
||||
request.currency,
|
||||
minCurrencyAmountMajorUnits);
|
||||
if (minCurrencyAmountMinorUnits.compareTo(amount) > 0) {
|
||||
throw new BadRequestException(Response.status(Response.Status.BAD_REQUEST)
|
||||
.entity(Map.of(
|
||||
"error", "amount_below_currency_minimum",
|
||||
"minimum", minCurrencyAmountMajorUnits.toString())).build());
|
||||
}
|
||||
|
||||
if (request.paymentMethod == PaymentMethod.SEPA_DEBIT &&
|
||||
amount.compareTo(SubscriptionCurrencyUtil.convertConfiguredAmountToApiAmount(
|
||||
EURO_CURRENCY_CODE,
|
||||
oneTimeDonationConfiguration.sepaMaximumEuros())) > 0) {
|
||||
throw new BadRequestException(Response.status(Response.Status.BAD_REQUEST)
|
||||
.entity(Map.of(
|
||||
"error", "amount_above_sepa_limit",
|
||||
"maximum", oneTimeDonationConfiguration.sepaMaximumEuros().toString())).build());
|
||||
}
|
||||
}
|
||||
|
||||
public static class CreatePayPalBoostRequest extends CreateBoostRequest {
|
||||
@@ -237,44 +249,32 @@ public class OneTimeDonationController {
|
||||
}
|
||||
}
|
||||
|
||||
record CreatePayPalBoostResponse(String approvalUrl, String paymentId) {}
|
||||
public record CreatePayPalBoostResponse(String approvalUrl, String paymentId) {}
|
||||
|
||||
@POST
|
||||
@Path("/paypal/create")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public CompletableFuture<Response> createPayPalBoost(
|
||||
@Auth Optional<AuthenticatedDevice> authenticatedAccount,
|
||||
@NotNull @Valid CreatePayPalBoostRequest request,
|
||||
@Context ContainerRequestContext containerRequestContext) {
|
||||
@ManagedAsync
|
||||
public CreatePayPalBoostResponse createPayPalBoost(
|
||||
@Auth final Optional<AuthenticatedDevice> authenticatedAccount,
|
||||
@NotNull @Valid final CreatePayPalBoostRequest request,
|
||||
@Context final ContainerRequestContext containerRequestContext) throws IOException {
|
||||
|
||||
if (authenticatedAccount.isPresent()) {
|
||||
throw new ForbiddenException("must not use authenticated connection for one-time donation operations");
|
||||
}
|
||||
|
||||
return CompletableFuture.runAsync(() ->
|
||||
validateRequestCurrencyAmount(request, BigDecimal.valueOf(request.amount), braintreeManager))
|
||||
.thenCompose(_ -> {
|
||||
final List<Locale> acceptableLanguages =
|
||||
HeaderUtils.getAcceptableLanguagesForRequest(containerRequestContext);
|
||||
|
||||
// These two localizations are a best-effort, and it's possible that the first `locale` and the localized line
|
||||
// item name will not match. We could try to align with the locales PayPal documents <https://developer.paypal.com/reference/locale-codes/#supported-locale-codes>
|
||||
// but that's a moving target, and we can hopefully have one of them be better for the user by selecting
|
||||
// independently.
|
||||
final Locale locale = acceptableLanguages.stream()
|
||||
.filter(l -> !"*".equals(l.getLanguage()))
|
||||
.findFirst()
|
||||
.orElse(Locale.US);
|
||||
final String localizedLineItemName = payPalDonationsTranslator.translate(acceptableLanguages,
|
||||
PayPalDonationsTranslator.ONE_TIME_DONATION_LINE_ITEM_KEY);
|
||||
|
||||
return braintreeManager.createOneTimePayment(request.currency.toUpperCase(Locale.ROOT), request.amount,
|
||||
locale.toLanguageTag(),
|
||||
request.returnUrl, request.cancelUrl, localizedLineItemName);
|
||||
})
|
||||
.thenApply(approvalDetails -> Response.ok(
|
||||
new CreatePayPalBoostResponse(approvalDetails.approvalUrl(), approvalDetails.paymentId())).build());
|
||||
validateRequestCurrencyAmount(request, BigDecimal.valueOf(request.amount), braintreeManager);
|
||||
final List<Locale> acceptableLanguages =
|
||||
HeaderUtils.getAcceptableLanguagesForRequest(containerRequestContext);
|
||||
final OneTimeDonationUtil.LocalizedPayPalDonationLineItem localizedLineItem = OneTimeDonationUtil.localizePayPalDonationLineItem(
|
||||
payPalDonationsTranslator, acceptableLanguages);
|
||||
final BraintreeManager.PayPalOneTimePaymentApprovalDetails approvalDetails =
|
||||
braintreeManager.createOneTimePayment(request.currency.toUpperCase(Locale.ROOT), request.amount,
|
||||
localizedLineItem.locale().toLanguageTag(),
|
||||
request.returnUrl, request.cancelUrl, localizedLineItem.itemName());
|
||||
return new CreatePayPalBoostResponse(approvalDetails.approvalUrl(), approvalDetails.paymentId());
|
||||
}
|
||||
|
||||
public static class ConfirmPayPalBoostRequest extends CreateBoostRequest {
|
||||
@@ -291,30 +291,28 @@ public class OneTimeDonationController {
|
||||
}
|
||||
}
|
||||
|
||||
record ConfirmPayPalBoostResponse(String paymentId) {}
|
||||
public record ConfirmPayPalBoostResponse(String paymentId) {}
|
||||
|
||||
@POST
|
||||
@Path("/paypal/confirm")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public CompletableFuture<Response> confirmPayPalBoost(
|
||||
@Auth Optional<AuthenticatedDevice> authenticatedAccount,
|
||||
@NotNull @Valid ConfirmPayPalBoostRequest request,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent) {
|
||||
@ManagedAsync
|
||||
public ConfirmPayPalBoostResponse confirmPayPalBoost(
|
||||
@Auth final Optional<AuthenticatedDevice> authenticatedAccount,
|
||||
@NotNull @Valid final ConfirmPayPalBoostRequest request,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent) throws SubscriptionProcessorException, IOException {
|
||||
|
||||
if (authenticatedAccount.isPresent()) {
|
||||
throw new ForbiddenException("must not use authenticated connection for one-time donation operations");
|
||||
}
|
||||
|
||||
return CompletableFuture.runAsync(() ->
|
||||
validateRequestCurrencyAmount(request, BigDecimal.valueOf(request.amount), braintreeManager))
|
||||
.thenCompose(_ -> braintreeManager.captureOneTimePayment(request.payerId, request.paymentId,
|
||||
request.paymentToken, request.currency, request.amount, request.level, getClientPlatform(userAgent)))
|
||||
.thenApply(chargeSuccessDetails -> {
|
||||
oneTimeDonationsManager.putPaidAt(chargeSuccessDetails.paymentId(), Instant.now());
|
||||
return Response.ok(
|
||||
new ConfirmPayPalBoostResponse(chargeSuccessDetails.paymentId())).build();
|
||||
});
|
||||
validateRequestCurrencyAmount(request, BigDecimal.valueOf(request.amount), braintreeManager);
|
||||
final BraintreeManager.PayPalChargeSuccessDetails chargeSuccessDetails = braintreeManager.captureOneTimePayment(
|
||||
request.payerId, request.paymentId,
|
||||
request.paymentToken, request.currency, request.amount, request.level, getClientPlatform(userAgent));
|
||||
oneTimeDonationsManager.putPaidAt(chargeSuccessDetails.paymentId(), Instant.now());
|
||||
return new ConfirmPayPalBoostResponse(chargeSuccessDetails.paymentId());
|
||||
}
|
||||
|
||||
public static class CreateBoostReceiptCredentialsRequest {
|
||||
@@ -341,98 +339,76 @@ public class OneTimeDonationController {
|
||||
@Path("/receipt_credentials")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public CompletableFuture<Response> createBoostReceiptCredentials(
|
||||
@Auth Optional<AuthenticatedDevice> authenticatedAccount,
|
||||
@ManagedAsync
|
||||
public Response createBoostReceiptCredentials(
|
||||
@Auth final Optional<AuthenticatedDevice> authenticatedAccount,
|
||||
@NotNull @Valid final CreateBoostReceiptCredentialsRequest request,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent) {
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent) throws IOException {
|
||||
|
||||
if (authenticatedAccount.isPresent()) {
|
||||
throw new ForbiddenException("must not use authenticated connection for one-time donation operations");
|
||||
}
|
||||
|
||||
final CompletableFuture<PaymentDetails> paymentDetailsFut = switch (request.processor) {
|
||||
final Optional<PaymentDetails> maybePaymentDetails = (switch (request.processor) {
|
||||
case STRIPE -> stripeManager.getPaymentDetails(request.paymentIntentId);
|
||||
case BRAINTREE -> braintreeManager.getPaymentDetails(request.paymentIntentId);
|
||||
case GOOGLE_PLAY_BILLING -> throw new BadRequestException("cannot use play billing for one-time donations");
|
||||
case APPLE_APP_STORE -> throw new BadRequestException("cannot use app store purchases for one-time donations");
|
||||
};
|
||||
|
||||
return paymentDetailsFut.thenApply(paymentDetails -> {
|
||||
if (paymentDetails == null) {
|
||||
throw new WebApplicationException(Response.Status.NOT_FOUND);
|
||||
} else if (paymentDetails.status() == PaymentStatus.PROCESSING) {
|
||||
return Response.noContent().build();
|
||||
} else if (paymentDetails.status() != PaymentStatus.SUCCEEDED) {
|
||||
throw new WebApplicationException(Response.status(Response.Status.PAYMENT_REQUIRED)
|
||||
.entity(new CreateBoostReceiptCredentialsErrorResponse(paymentDetails.chargeFailure())).build());
|
||||
}
|
||||
|
||||
// The payment was successful, try to issue the receipt credential
|
||||
|
||||
long level = oneTimeDonationConfiguration.boost().level();
|
||||
if (paymentDetails.customMetadata() != null) {
|
||||
String levelMetadata = paymentDetails.customMetadata()
|
||||
.getOrDefault("level", Long.toString(oneTimeDonationConfiguration.boost().level()));
|
||||
try {
|
||||
level = Long.parseLong(levelMetadata);
|
||||
} catch (NumberFormatException e) {
|
||||
logger.error("failed to parse level metadata ({}) on payment intent {}", levelMetadata,
|
||||
paymentDetails.id(), e);
|
||||
throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
}
|
||||
Duration levelExpiration;
|
||||
if (oneTimeDonationConfiguration.boost().level() == level) {
|
||||
levelExpiration = oneTimeDonationConfiguration.boost().expiration();
|
||||
} else if (oneTimeDonationConfiguration.gift().level() == level) {
|
||||
levelExpiration = oneTimeDonationConfiguration.gift().expiration();
|
||||
} else {
|
||||
logger.error("level ({}) returned from payment intent that is unknown to the server", level);
|
||||
throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
ReceiptCredentialRequest receiptCredentialRequest;
|
||||
try {
|
||||
receiptCredentialRequest = new ReceiptCredentialRequest(request.receiptCredentialRequest);
|
||||
} catch (InvalidInputException e) {
|
||||
throw new BadRequestException("invalid receipt credential request", e);
|
||||
}
|
||||
final long finalLevel = level;
|
||||
try {
|
||||
issuedReceiptsManager.recordIssuance(paymentDetails.id(), request.processor,
|
||||
receiptCredentialRequest, clock.instant());
|
||||
} catch (final WriteConflictException _) {
|
||||
throw new WebApplicationException(Response.Status.CONFLICT);
|
||||
}
|
||||
final Instant paidAt = oneTimeDonationsManager.getPaidAt(paymentDetails.id(), paymentDetails.created());
|
||||
final Instant expiration = paidAt
|
||||
.plus(levelExpiration)
|
||||
.truncatedTo(ChronoUnit.DAYS)
|
||||
.plus(1, ChronoUnit.DAYS);
|
||||
final ReceiptCredentialResponse receiptCredentialResponse;
|
||||
try {
|
||||
receiptCredentialResponse = zkReceiptOperations.issueReceiptCredential(
|
||||
receiptCredentialRequest, expiration.getEpochSecond(), finalLevel);
|
||||
} catch (final VerificationFailedException e) {
|
||||
throw new BadRequestException("receipt credential request failed verification", e);
|
||||
}
|
||||
Metrics.counter(SubscriptionController.RECEIPT_ISSUED_COUNTER_NAME,
|
||||
Tags.of(
|
||||
Tag.of(SubscriptionController.PROCESSOR_TAG_NAME, request.processor.toString()),
|
||||
Tag.of(SubscriptionController.TYPE_TAG_NAME, "boost"),
|
||||
UserAgentTagUtil.getPlatformTag(userAgent)))
|
||||
.increment();
|
||||
return Response.ok(
|
||||
new CreateBoostReceiptCredentialsSuccessResponse(receiptCredentialResponse.serialize()))
|
||||
.build();
|
||||
});
|
||||
}
|
||||
|
||||
@Nullable
|
||||
private static ClientPlatform getClientPlatform(@Nullable final String userAgentString) {
|
||||
try {
|
||||
return UserAgentUtil.parseUserAgentString(userAgentString).platform();
|
||||
} catch (final UnrecognizedUserAgentException e) {
|
||||
return null;
|
||||
if (maybePaymentDetails.isEmpty()) {
|
||||
throw new WebApplicationException(Response.Status.NOT_FOUND);
|
||||
}
|
||||
final PaymentDetails paymentDetails = maybePaymentDetails.get();
|
||||
if (paymentDetails.status() == PaymentStatus.PROCESSING) {
|
||||
return Response.noContent().build();
|
||||
}
|
||||
if (paymentDetails.status() != PaymentStatus.SUCCEEDED) {
|
||||
throw new WebApplicationException(Response.status(Response.Status.PAYMENT_REQUIRED)
|
||||
.entity(new CreateBoostReceiptCredentialsErrorResponse(paymentDetails.chargeFailure())).build());
|
||||
}
|
||||
|
||||
// The payment was successful, try to issue the receipt credential
|
||||
|
||||
final OneTimeDonationUtil.DonationLevelDetails levelDetails;
|
||||
try {
|
||||
levelDetails = OneTimeDonationUtil.getLevelDetails(paymentDetails, oneTimeDonationConfiguration);
|
||||
} catch (OneTimeDonationUtil.InvalidLevelException _) {
|
||||
throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
|
||||
final ReceiptCredentialRequest receiptCredentialRequest;
|
||||
try {
|
||||
receiptCredentialRequest = new ReceiptCredentialRequest(request.receiptCredentialRequest);
|
||||
} catch (final InvalidInputException e) {
|
||||
throw new BadRequestException("invalid receipt credential request", e);
|
||||
}
|
||||
try {
|
||||
issuedReceiptsManager.recordIssuance(paymentDetails.id(), request.processor,
|
||||
receiptCredentialRequest, clock.instant());
|
||||
} catch (WriteConflictException _) {
|
||||
throw new WebApplicationException(Response.Status.CONFLICT);
|
||||
}
|
||||
final Instant paidAt = oneTimeDonationsManager.getPaidAt(paymentDetails.id(), paymentDetails.created());
|
||||
final Instant expiration = paidAt
|
||||
.plus(levelDetails.levelExpiration())
|
||||
.truncatedTo(ChronoUnit.DAYS)
|
||||
.plus(1, ChronoUnit.DAYS);
|
||||
final ReceiptCredentialResponse receiptCredentialResponse;
|
||||
try {
|
||||
receiptCredentialResponse = zkReceiptOperations.issueReceiptCredential(
|
||||
receiptCredentialRequest, expiration.getEpochSecond(), levelDetails.level());
|
||||
} catch (final VerificationFailedException e) {
|
||||
throw new BadRequestException("receipt credential request failed verification", e);
|
||||
}
|
||||
Metrics.counter(SubscriptionController.RECEIPT_ISSUED_COUNTER_NAME,
|
||||
Tags.of(
|
||||
Tag.of(SubscriptionController.PROCESSOR_TAG_NAME, request.processor.toString()),
|
||||
Tag.of(SubscriptionController.TYPE_TAG_NAME, "boost"),
|
||||
UserAgentTagUtil.getPlatformTag(userAgent)))
|
||||
.increment();
|
||||
return Response.ok(
|
||||
new CreateBoostReceiptCredentialsSuccessResponse(receiptCredentialResponse.serialize()))
|
||||
.build();
|
||||
}
|
||||
}
|
||||
+6
-13
@@ -39,7 +39,6 @@ import jakarta.ws.rs.core.Response;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.time.Clock;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
@@ -88,7 +87,6 @@ import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimitedByIp;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.s3.PolicySigner;
|
||||
import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountBadge;
|
||||
@@ -114,7 +112,6 @@ public class ProfileController {
|
||||
private final ProfileBadgeConverter profileBadgeConverter;
|
||||
private final Map<String, BadgeConfiguration> badgeConfigurationMap;
|
||||
|
||||
private final PolicySigner policySigner;
|
||||
private final PostPolicyGenerator policyGenerator;
|
||||
private final ServerSecretParams serverSecretParams;
|
||||
private final ServerZkProfileOperations zkProfileOperations;
|
||||
@@ -135,7 +132,6 @@ public class ProfileController {
|
||||
ProfileBadgeConverter profileBadgeConverter,
|
||||
BadgesConfiguration badgesConfiguration,
|
||||
PostPolicyGenerator policyGenerator,
|
||||
PolicySigner policySigner,
|
||||
ServerSecretParams serverSecretParams,
|
||||
ServerZkProfileOperations zkProfileOperations,
|
||||
Executor batchIdentityCheckExecutor) {
|
||||
@@ -150,7 +146,6 @@ public class ProfileController {
|
||||
this.serverSecretParams = serverSecretParams;
|
||||
this.zkProfileOperations = zkProfileOperations;
|
||||
this.policyGenerator = policyGenerator;
|
||||
this.policySigner = policySigner;
|
||||
this.batchIdentityCheckExecutor = Preconditions.checkNotNull(batchIdentityCheckExecutor);
|
||||
}
|
||||
|
||||
@@ -553,15 +548,13 @@ public class ProfileController {
|
||||
return maybeTargetAccount.get();
|
||||
}
|
||||
|
||||
private ProfileAvatarUploadAttributes generateAvatarUploadForm(
|
||||
final String objectName) {
|
||||
ZonedDateTime now = ZonedDateTime.now(clock);
|
||||
Pair<String, String> policy = policyGenerator.createFor(now, objectName, ProfileHelper.MAX_PROFILE_AVATAR_SIZE_BYTES);
|
||||
String signature = policySigner.getSignature(now, policy.second());
|
||||
private ProfileAvatarUploadAttributes generateAvatarUploadForm(final String objectName) {
|
||||
final PostPolicyGenerator.SignedPostPolicy signedPostPolicy =
|
||||
policyGenerator.createFor(objectName, ProfileHelper.MAX_PROFILE_AVATAR_SIZE_BYTES, clock.instant());
|
||||
|
||||
return new ProfileAvatarUploadAttributes(objectName, policy.first(),
|
||||
"private", "AWS4-HMAC-SHA256",
|
||||
now.format(PostPolicyGenerator.AWS_DATE_TIME), policy.second(), signature);
|
||||
return new ProfileAvatarUploadAttributes(objectName, signedPostPolicy.credential(),
|
||||
PostPolicyGenerator.ACL, PostPolicyGenerator.ALGORITHM,
|
||||
signedPostPolicy.formattedTimestamp(), signedPostPolicy.encodedPolicy(), signedPostPolicy.signature());
|
||||
}
|
||||
|
||||
private static Map<String, Boolean> getAccountCapabilities(final Account account) {
|
||||
|
||||
+29
-27
@@ -6,6 +6,7 @@
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.dropwizard.util.DataSize;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.validation.constraints.Max;
|
||||
import jakarta.validation.constraints.Min;
|
||||
@@ -15,8 +16,8 @@ import jakarta.ws.rs.PathParam;
|
||||
import jakarta.ws.rs.Produces;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import java.security.SecureRandom;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.util.HexFormat;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
@@ -24,23 +25,25 @@ import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.entities.StickerPackFormUploadAttributes;
|
||||
import org.whispersystems.textsecuregcm.entities.StickerPackFormUploadAttributes.StickerPackFormUploadItem;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.s3.PolicySigner;
|
||||
import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
|
||||
import org.whispersystems.textsecuregcm.util.Constants;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
|
||||
@Path("/v1/sticker")
|
||||
@Tag(name = "Stickers")
|
||||
public class StickerController {
|
||||
|
||||
private final RateLimiters rateLimiters;
|
||||
private final PolicySigner policySigner;
|
||||
private final PostPolicyGenerator policyGenerator;
|
||||
private final Clock clock;
|
||||
|
||||
public StickerController(RateLimiters rateLimiters, String accessKey, String accessSecret, String region, String bucket) {
|
||||
public static final int MAXIMUM_STICKER_SIZE_BYTES = (int) DataSize.kibibytes(300 + 1).toBytes(); // add 1 kiB for encryption overhead
|
||||
public static final int MAXIMUM_STICKER_MANIFEST_SIZE_BYTES = (int) DataSize.kibibytes(10).toBytes();
|
||||
|
||||
public StickerController(final RateLimiters rateLimiters,
|
||||
final PostPolicyGenerator postPolicyGenerator,
|
||||
final Clock clock) {
|
||||
this.rateLimiters = rateLimiters;
|
||||
this.policySigner = new PolicySigner(accessSecret, region);
|
||||
this.policyGenerator = new PostPolicyGenerator(region, bucket, accessKey);
|
||||
this.policyGenerator = postPolicyGenerator;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
@GET
|
||||
@@ -51,33 +54,32 @@ public class StickerController {
|
||||
throws RateLimitExceededException {
|
||||
rateLimiters.getStickerPackLimiter().validate(auth.accountIdentifier());
|
||||
|
||||
ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC);
|
||||
String packId = generatePackId();
|
||||
String packLocation = "stickers/" + packId;
|
||||
String manifestKey = packLocation + "/manifest.proto";
|
||||
Pair<String, String> manifestPolicy = policyGenerator.createFor(now, manifestKey,
|
||||
Constants.MAXIMUM_STICKER_MANIFEST_SIZE_BYTES);
|
||||
String manifestSignature = policySigner.getSignature(now, manifestPolicy.second());
|
||||
StickerPackFormUploadItem manifest = new StickerPackFormUploadItem(-1, manifestKey, manifestPolicy.first(),
|
||||
"private", "AWS4-HMAC-SHA256",
|
||||
now.format(PostPolicyGenerator.AWS_DATE_TIME), manifestPolicy.second(), manifestSignature);
|
||||
final Instant currentTime = clock.instant();
|
||||
final String packId = generatePackId();
|
||||
final String packLocation = "stickers/" + packId;
|
||||
final String manifestKey = packLocation + "/manifest.proto";
|
||||
final PostPolicyGenerator.SignedPostPolicy manifestPolicy =
|
||||
policyGenerator.createFor(manifestKey, MAXIMUM_STICKER_MANIFEST_SIZE_BYTES, currentTime);
|
||||
|
||||
List<StickerPackFormUploadItem> stickers = new LinkedList<>();
|
||||
final StickerPackFormUploadItem manifest = new StickerPackFormUploadItem(-1, manifestKey, manifestPolicy.credential(),
|
||||
PostPolicyGenerator.ACL, PostPolicyGenerator.ALGORITHM,
|
||||
manifestPolicy.formattedTimestamp(), manifestPolicy.encodedPolicy(), manifestPolicy.signature());
|
||||
|
||||
final List<StickerPackFormUploadItem> stickers = new LinkedList<>();
|
||||
|
||||
for (int i = 0; i < stickerCount; i++) {
|
||||
String stickerKey = packLocation + "/full/" + i;
|
||||
Pair<String, String> stickerPolicy = policyGenerator.createFor(now, stickerKey,
|
||||
Constants.MAXIMUM_STICKER_SIZE_BYTES);
|
||||
String stickerSignature = policySigner.getSignature(now, stickerPolicy.second());
|
||||
stickers.add(new StickerPackFormUploadItem(i, stickerKey, stickerPolicy.first(), "private", "AWS4-HMAC-SHA256",
|
||||
now.format(PostPolicyGenerator.AWS_DATE_TIME), stickerPolicy.second(), stickerSignature));
|
||||
final String stickerKey = packLocation + "/full/" + i;
|
||||
final PostPolicyGenerator.SignedPostPolicy stickerPolicy =
|
||||
policyGenerator.createFor(stickerKey, MAXIMUM_STICKER_SIZE_BYTES, currentTime);
|
||||
stickers.add(new StickerPackFormUploadItem(i, stickerKey, stickerPolicy.credential(), PostPolicyGenerator.ACL, PostPolicyGenerator.ALGORITHM,
|
||||
manifestPolicy.formattedTimestamp(), stickerPolicy.encodedPolicy(), stickerPolicy.signature()));
|
||||
}
|
||||
|
||||
return new StickerPackFormUploadAttributes(packId, manifest, stickers);
|
||||
}
|
||||
|
||||
private String generatePackId() {
|
||||
byte[] object = new byte[16];
|
||||
final byte[] object = new byte[16];
|
||||
new SecureRandom().nextBytes(object);
|
||||
|
||||
return HexFormat.of().formatHex(object);
|
||||
|
||||
+91
-156
@@ -5,6 +5,11 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil.buildCurrencyConfiguration;
|
||||
import static org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil.buildDonationLevelsConfiguration;
|
||||
import static org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil.getClientPlatform;
|
||||
import static org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil.getPayPalLocale;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import com.fasterxml.jackson.annotation.JsonInclude.Include;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
@@ -15,6 +20,7 @@ import io.micrometer.core.instrument.Tag;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import io.swagger.v3.oas.annotations.ExternalDocumentation;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.headers.Header;
|
||||
import io.swagger.v3.oas.annotations.media.Content;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
@@ -36,44 +42,40 @@ import jakarta.ws.rs.Path;
|
||||
import jakarta.ws.rs.PathParam;
|
||||
import jakarta.ws.rs.Produces;
|
||||
import jakarta.ws.rs.QueryParam;
|
||||
import jakarta.ws.rs.WebApplicationException;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import jakarta.ws.rs.core.Context;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import jakarta.ws.rs.core.Response.Status;
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.math.BigDecimal;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.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.VerificationFailedException;
|
||||
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialResponse;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.DonationPermitHeader;
|
||||
import org.whispersystems.textsecuregcm.badges.BadgeTranslator;
|
||||
import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration;
|
||||
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.grpc.SubscriptionsUtil;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimitedByIp;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
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.DonationPermitsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.SubscriberCredentials;
|
||||
import org.whispersystems.textsecuregcm.storage.SubscriptionManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Subscriptions;
|
||||
@@ -82,8 +84,10 @@ import org.whispersystems.textsecuregcm.subscriptions.BankMandateTranslator;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.BankTransferType;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.BraintreeManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.ChargeFailure;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.CurrencyConfiguration;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.CustomerAwareSubscriptionPaymentProcessor;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.GooglePlayBillingManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.LevelConfiguration;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentMethod;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.ProcessorCustomer;
|
||||
@@ -94,9 +98,6 @@ import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidLevelEx
|
||||
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;
|
||||
import org.whispersystems.textsecuregcm.util.ua.UserAgentUtil;
|
||||
|
||||
@Path("/v1/subscription")
|
||||
@io.swagger.v3.oas.annotations.tags.Tag(name = "Subscriptions")
|
||||
@@ -112,24 +113,26 @@ public class SubscriptionController {
|
||||
private final AppleAppStoreManager appleAppStoreManager;
|
||||
private final BadgeTranslator badgeTranslator;
|
||||
private final BankMandateTranslator bankMandateTranslator;
|
||||
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
|
||||
private final DonationPermitsManager donationPermitsManager;
|
||||
private final long backupMediaStorageAllowanceBytes;
|
||||
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";
|
||||
private static final String SUBSCRIPTION_TYPE_TAG_NAME = "subscriptionType";
|
||||
|
||||
public SubscriptionController(
|
||||
@Nonnull Clock clock,
|
||||
@Nonnull SubscriptionConfiguration subscriptionConfiguration,
|
||||
@Nonnull OneTimeDonationConfiguration oneTimeDonationConfiguration,
|
||||
@Nonnull SubscriptionManager subscriptionManager,
|
||||
@Nonnull StripeManager stripeManager,
|
||||
@Nonnull BraintreeManager braintreeManager,
|
||||
@Nonnull GooglePlayBillingManager googlePlayBillingManager,
|
||||
@Nonnull AppleAppStoreManager appleAppStoreManager,
|
||||
@Nonnull BadgeTranslator badgeTranslator,
|
||||
@Nonnull BankMandateTranslator bankMandateTranslator,
|
||||
@NotNull DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
|
||||
Clock clock,
|
||||
SubscriptionConfiguration subscriptionConfiguration,
|
||||
OneTimeDonationConfiguration oneTimeDonationConfiguration,
|
||||
SubscriptionManager subscriptionManager,
|
||||
StripeManager stripeManager,
|
||||
BraintreeManager braintreeManager,
|
||||
GooglePlayBillingManager googlePlayBillingManager,
|
||||
AppleAppStoreManager appleAppStoreManager,
|
||||
BadgeTranslator badgeTranslator,
|
||||
BankMandateTranslator bankMandateTranslator,
|
||||
DonationPermitsManager donationPermitsManager,
|
||||
long backupMediaStorageAllowanceBytes) {
|
||||
this.subscriptionManager = subscriptionManager;
|
||||
this.clock = Objects.requireNonNull(clock);
|
||||
this.subscriptionConfiguration = Objects.requireNonNull(subscriptionConfiguration);
|
||||
@@ -140,91 +143,29 @@ public class SubscriptionController {
|
||||
this.appleAppStoreManager = appleAppStoreManager;
|
||||
this.badgeTranslator = Objects.requireNonNull(badgeTranslator);
|
||||
this.bankMandateTranslator = Objects.requireNonNull(bankMandateTranslator);
|
||||
this.dynamicConfigurationManager = dynamicConfigurationManager;
|
||||
this.donationPermitsManager = donationPermitsManager;
|
||||
this.backupMediaStorageAllowanceBytes = backupMediaStorageAllowanceBytes;
|
||||
}
|
||||
|
||||
private Map<String, CurrencyConfiguration> buildCurrencyConfiguration() {
|
||||
final List<CustomerAwareSubscriptionPaymentProcessor> subscriptionPaymentProcessors = List.of(stripeManager, braintreeManager);
|
||||
return oneTimeDonationConfiguration.currencies()
|
||||
.entrySet().stream()
|
||||
.collect(Collectors.toMap(Entry::getKey, currencyAndConfig -> {
|
||||
final String currency = currencyAndConfig.getKey();
|
||||
final OneTimeDonationCurrencyConfiguration currencyConfig = currencyAndConfig.getValue();
|
||||
|
||||
final Map<String, List<BigDecimal>> oneTimeLevelsToSuggestedAmounts = Map.of(
|
||||
String.valueOf(oneTimeDonationConfiguration.boost().level()), currencyConfig.boosts(),
|
||||
String.valueOf(oneTimeDonationConfiguration.gift().level()), List.of(currencyConfig.gift())
|
||||
);
|
||||
|
||||
final Function<Map<Long, ? extends SubscriptionLevelConfiguration>, Map<String, BigDecimal>> extractSubscriptionAmounts = levels ->
|
||||
levels.entrySet().stream()
|
||||
.filter(levelIdAndConfig -> levelIdAndConfig.getValue().prices().containsKey(currency))
|
||||
.collect(Collectors.toMap(
|
||||
levelIdAndConfig -> String.valueOf(levelIdAndConfig.getKey()),
|
||||
levelIdAndConfig -> levelIdAndConfig.getValue().prices().get(currency).amount()));
|
||||
|
||||
final List<String> supportedPaymentMethods = Arrays.stream(PaymentMethod.values())
|
||||
.filter(paymentMethod -> subscriptionPaymentProcessors.stream()
|
||||
.anyMatch(manager -> manager.supportsPaymentMethod(paymentMethod)
|
||||
&& manager.getSupportedCurrenciesForPaymentMethod(paymentMethod).contains(currency)))
|
||||
.map(PaymentMethod::name)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
if (supportedPaymentMethods.isEmpty()) {
|
||||
throw new RuntimeException("Configuration has currency with no processor support: " + currency);
|
||||
}
|
||||
|
||||
return new CurrencyConfiguration(
|
||||
currencyConfig.minimum(),
|
||||
oneTimeLevelsToSuggestedAmounts,
|
||||
extractSubscriptionAmounts.apply(subscriptionConfiguration.getDonationLevels()),
|
||||
extractSubscriptionAmounts.apply(subscriptionConfiguration.getBackupLevels()),
|
||||
supportedPaymentMethods);
|
||||
}));
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
GetSubscriptionConfigurationResponse buildGetSubscriptionConfigurationResponse(
|
||||
final List<Locale> acceptableLanguages) {
|
||||
final Map<String, LevelConfiguration> donationLevels = new HashMap<>();
|
||||
|
||||
subscriptionConfiguration.getDonationLevels().forEach((levelId, levelConfig) -> {
|
||||
final LevelConfiguration levelConfiguration = new LevelConfiguration(
|
||||
"" /* deprecated and unused */,
|
||||
badgeTranslator.translate(acceptableLanguages, levelConfig.badge()));
|
||||
donationLevels.put(String.valueOf(levelId), levelConfiguration);
|
||||
});
|
||||
|
||||
final Badge boostBadge = badgeTranslator.translate(acceptableLanguages,
|
||||
oneTimeDonationConfiguration.boost().badge());
|
||||
donationLevels.put(String.valueOf(oneTimeDonationConfiguration.boost().level()),
|
||||
new LevelConfiguration(
|
||||
"" /* deprecated and unused */,
|
||||
// NB: the one-time badges are PurchasableBadge, which has a `duration` field
|
||||
new PurchasableBadge(
|
||||
boostBadge,
|
||||
oneTimeDonationConfiguration.boost().expiration())));
|
||||
|
||||
final Badge giftBadge = badgeTranslator.translate(acceptableLanguages, oneTimeDonationConfiguration.gift().badge());
|
||||
donationLevels.put(String.valueOf(oneTimeDonationConfiguration.gift().level()),
|
||||
new LevelConfiguration(
|
||||
"" /* deprecated and unused */,
|
||||
new PurchasableBadge(
|
||||
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(
|
||||
maxTotalBackupMediaBytes,
|
||||
backupMediaStorageAllowanceBytes,
|
||||
e.getValue().playProductId(),
|
||||
e.getValue().mediaTtl().toDays())));
|
||||
|
||||
return new GetSubscriptionConfigurationResponse(buildCurrencyConfiguration(), donationLevels,
|
||||
return new GetSubscriptionConfigurationResponse(
|
||||
buildCurrencyConfiguration(List.of(stripeManager, braintreeManager), oneTimeDonationConfiguration,
|
||||
subscriptionConfiguration),
|
||||
buildDonationLevelsConfiguration(subscriptionConfiguration, oneTimeDonationConfiguration, badgeTranslator,
|
||||
acceptableLanguages),
|
||||
new BackupConfiguration(backupLevels, subscriptionConfiguration.getbackupFreeTierMediaDuration().toDays()),
|
||||
oneTimeDonationConfiguration.sepaMaximumEuros());
|
||||
}
|
||||
@@ -267,15 +208,35 @@ public class SubscriptionController {
|
||||
period of time will result in the subscription being canceled.
|
||||
""")
|
||||
@ApiResponse(responseCode = "200", description = "The subscriber was successfully created or refreshed")
|
||||
@ApiResponse(responseCode = "401", description = "Donation permit was invalid or already spent")
|
||||
@ApiResponse(responseCode = "403", description = "subscriberId authentication failure OR account authentication is present")
|
||||
@ApiResponse(responseCode = "404", description = "subscriberId is malformed")
|
||||
@ManagedAsync
|
||||
public Response updateSubscriber(
|
||||
@Auth Optional<AuthenticatedDevice> authenticatedAccount,
|
||||
|
||||
@Parameter(description="A base64-encoded donation permit retrieved from POST /v1/donation/permit. Not required if the subscriber already exists.")
|
||||
@HeaderParam(HeaderUtils.DONATION_PERMIT)
|
||||
final Optional<DonationPermitHeader> donationPermitHeader,
|
||||
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) @Nullable final String userAgent,
|
||||
|
||||
@PathParam("subscriberId") String subscriberId) throws SubscriptionException {
|
||||
SubscriberCredentials subscriberCredentials =
|
||||
SubscriberCredentials.process(authenticatedAccount, subscriberId, clock);
|
||||
subscriptionManager.updateSubscriber(subscriberCredentials);
|
||||
|
||||
SubscriptionsUtil.recordDonationPermitPresent(donationPermitHeader.isPresent(), "putSubscriber", userAgent);
|
||||
final boolean creationPermitted = donationPermitHeader.map(
|
||||
permitHeader -> {
|
||||
try {
|
||||
return SubscriptionsUtil.verifyAndSpendDonationPermit(permitHeader.permit(), donationPermitsManager, clock);
|
||||
} catch (VerificationFailedException e) {
|
||||
return false;
|
||||
}
|
||||
})
|
||||
.orElse(true);
|
||||
|
||||
subscriptionManager.updateSubscriber(subscriberCredentials, creationPermitted);
|
||||
return Response.ok().build();
|
||||
}
|
||||
|
||||
@@ -291,6 +252,11 @@ public class SubscriptionController {
|
||||
@RateLimitedByIp(RateLimiters.For.ADD_SUBSCRIPTION_PAYMENT_METHOD)
|
||||
public CreatePaymentMethodResponse createPaymentMethod(
|
||||
@Auth Optional<AuthenticatedDevice> authenticatedAccount,
|
||||
|
||||
@Parameter(description="A base64-encoded donation permit retrieved from POST /v1/donation/permit")
|
||||
@HeaderParam(HeaderUtils.DONATION_PERMIT)
|
||||
final Optional<DonationPermitHeader> donationPermitHeader,
|
||||
|
||||
@PathParam("subscriberId") String subscriberId,
|
||||
@QueryParam("type") @DefaultValue("CARD") PaymentMethod paymentMethodType,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) @Nullable final String userAgentString) throws SubscriptionException {
|
||||
@@ -308,6 +274,21 @@ public class SubscriptionController {
|
||||
case UNKNOWN -> throw new BadRequestException("Invalid payment method");
|
||||
};
|
||||
|
||||
SubscriptionsUtil.recordDonationPermitPresent(donationPermitHeader.isPresent(), "createPaymentMethod", userAgentString);
|
||||
final boolean spendSuccessful = donationPermitHeader.map(
|
||||
permitHeader -> {
|
||||
try {
|
||||
return SubscriptionsUtil.verifyAndSpendDonationPermit(permitHeader.permit(), donationPermitsManager, clock);
|
||||
} catch (VerificationFailedException e) {
|
||||
return false;
|
||||
}
|
||||
})
|
||||
.orElse(true);
|
||||
|
||||
if (!spendSuccessful) {
|
||||
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
|
||||
}
|
||||
|
||||
final String token = subscriptionManager.addPaymentMethodToCustomer(
|
||||
subscriberCredentials,
|
||||
customerAwareSubscriptionPaymentProcessor,
|
||||
@@ -332,23 +313,19 @@ public class SubscriptionController {
|
||||
@PathParam("subscriberId") String subscriberId,
|
||||
@NotNull @Valid CreatePayPalBillingAgreementRequest request,
|
||||
@Context ContainerRequestContext containerRequestContext,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) @Nullable final String userAgentString) throws SubscriptionException {
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) @Nullable final String userAgentString)
|
||||
throws SubscriptionException, IOException {
|
||||
|
||||
final SubscriberCredentials subscriberCredentials =
|
||||
SubscriberCredentials.process(authenticatedAccount, subscriberId, clock);
|
||||
final Locale locale = HeaderUtils.getAcceptableLanguagesForRequest(containerRequestContext).stream()
|
||||
.filter(l -> !"*".equals(l.getLanguage()))
|
||||
.findFirst()
|
||||
.orElse(Locale.US);
|
||||
final Locale locale = getPayPalLocale(HeaderUtils.getAcceptableLanguagesForRequest(containerRequestContext));
|
||||
|
||||
final BraintreeManager.PayPalBillingAgreementApprovalDetails billingAgreementApprovalDetails = subscriptionManager.addPaymentMethodToCustomer(
|
||||
subscriberCredentials,
|
||||
braintreeManager,
|
||||
getClientPlatform(userAgentString),
|
||||
(mgr, customerId) ->
|
||||
mgr.createPayPalBillingAgreement(request.returnUrl, request.cancelUrl, locale.toLanguageTag()))
|
||||
.join();
|
||||
return new CreatePayPalBillingAgreementResponse(
|
||||
(mgr, _) -> mgr.createPayPalBillingAgreement(request.returnUrl, request.cancelUrl, locale.toLanguageTag()));
|
||||
return new CreatePayPalBillingAgreementResponse(
|
||||
billingAgreementApprovalDetails.approvalUrl(),
|
||||
billingAgreementApprovalDetails.billingAgreementToken());
|
||||
}
|
||||
@@ -370,7 +347,7 @@ public class SubscriptionController {
|
||||
@Auth Optional<AuthenticatedDevice> authenticatedAccount,
|
||||
@PathParam("subscriberId") String subscriberId,
|
||||
@PathParam("processor") PaymentProvider processor,
|
||||
@PathParam("paymentMethodToken") @NotEmpty String paymentMethodToken) throws SubscriptionException {
|
||||
@PathParam("paymentMethodToken") @NotEmpty String paymentMethodToken) throws SubscriptionException, IOException {
|
||||
SubscriberCredentials subscriberCredentials =
|
||||
SubscriberCredentials.process(authenticatedAccount, subscriberId, clock);
|
||||
|
||||
@@ -542,33 +519,12 @@ public class SubscriptionController {
|
||||
@Schema(description = "A map of lower-cased ISO 3 currency codes to minimums and level-specific scalar amounts")
|
||||
Map<String, CurrencyConfiguration> currencies,
|
||||
@Schema(description = "A map of numeric donation level IDs to level-specific badge configuration")
|
||||
Map<String, LevelConfiguration> levels,
|
||||
Map<Long, LevelConfiguration> levels,
|
||||
@Schema(description = "Backup specific configuration")
|
||||
BackupConfiguration backup,
|
||||
@Schema(description = "The maximum value of a one-time donation SEPA transaction")
|
||||
BigDecimal sepaMaximumEuros) {}
|
||||
|
||||
@Schema(description = "Configuration for a currency - use to present appropriate client interfaces")
|
||||
public record CurrencyConfiguration(
|
||||
@Schema(description = "The minimum amount that may be submitted for a one-time donation in the currency")
|
||||
BigDecimal minimum,
|
||||
@Schema(description = "A map of numeric one-time donation level IDs to the list of default amounts to be presented")
|
||||
Map<String, List<BigDecimal>> oneTime,
|
||||
@Schema(description = "A map of numeric subscription level IDs to the amount charged for that level")
|
||||
Map<String, BigDecimal> subscription,
|
||||
@Schema(description = "A map of numeric backup level IDs to the amount charged for that level")
|
||||
Map<String, BigDecimal> backupSubscription,
|
||||
@Schema(description = "The payment methods that support the given currency")
|
||||
List<String> supportedPaymentMethods) {}
|
||||
|
||||
@Schema(description = "Configuration for a donation level - use to present appropriate client interfaces")
|
||||
public record LevelConfiguration(
|
||||
@Deprecated(forRemoval = true) // may be removed after 2025-01-28
|
||||
@Schema(description = "The localized name for the level")
|
||||
String name,
|
||||
@Schema(description = "The displayable badge associated with the level")
|
||||
Badge badge) {}
|
||||
|
||||
public record BackupConfiguration(
|
||||
@Schema(description = "A map of numeric backup level IDs to level-specific backup configuration")
|
||||
Map<String, BackupLevelConfiguration> levels,
|
||||
@@ -768,7 +724,8 @@ public class SubscriptionController {
|
||||
SubscriberCredentials subscriberCredentials = SubscriberCredentials.process(authenticatedAccount, subscriberId, clock);
|
||||
try {
|
||||
final SubscriptionManager.ReceiptResult receiptCredential = subscriptionManager.createReceiptCredentials(
|
||||
subscriberCredentials, request, this::receiptExpirationWithGracePeriod);
|
||||
subscriberCredentials, request.receiptCredentialRequest(),
|
||||
r -> SubscriptionsUtil.receiptExpirationWithGracePeriod(subscriptionConfiguration, r));
|
||||
|
||||
final ReceiptCredentialResponse receiptCredentialResponse = receiptCredential.receiptCredentialResponse();
|
||||
final CustomerAwareSubscriptionPaymentProcessor.ReceiptItem receipt = receiptCredential.receiptItem();
|
||||
@@ -794,18 +751,18 @@ public class SubscriptionController {
|
||||
public Response setDefaultPaymentMethodForIdeal(
|
||||
@Auth Optional<AuthenticatedDevice> authenticatedAccount,
|
||||
@PathParam("subscriberId") String subscriberId,
|
||||
@PathParam("setupIntentId") @NotEmpty String setupIntentId) throws SubscriptionException {
|
||||
@PathParam("setupIntentId") @NotEmpty String setupIntentId) throws SubscriptionException, IOException {
|
||||
SubscriberCredentials subscriberCredentials =
|
||||
SubscriberCredentials.process(authenticatedAccount, subscriberId, clock);
|
||||
|
||||
final String generatedSepaId = stripeManager.getGeneratedSepaIdFromSetupIntent(setupIntentId).join();
|
||||
final String generatedSepaId = stripeManager.getGeneratedSepaIdFromSetupIntent(setupIntentId);
|
||||
setDefaultPaymentMethod(stripeManager, generatedSepaId, subscriberCredentials);
|
||||
return Response.ok().build();
|
||||
}
|
||||
|
||||
private void setDefaultPaymentMethod(final CustomerAwareSubscriptionPaymentProcessor manager,
|
||||
final String paymentMethodId,
|
||||
final SubscriberCredentials requestData) throws SubscriptionException {
|
||||
final SubscriberCredentials requestData) throws SubscriptionException, IOException {
|
||||
try {
|
||||
final Subscriptions.Record record = subscriptionManager.getSubscriber(requestData);
|
||||
|
||||
@@ -816,26 +773,13 @@ public class SubscriptionController {
|
||||
|
||||
manager
|
||||
.setDefaultPaymentMethodForCustomer(processorCustomer.customerId(), paymentMethodId, record.subscriptionId);
|
||||
} catch (SubscriptionInvalidArgumentsException e) {
|
||||
} catch (final 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) {
|
||||
final PaymentTime paymentTime = receiptItem.paymentTime();
|
||||
return switch (subscriptionConfiguration.getSubscriptionLevel(receiptItem.level()).type()) {
|
||||
case DONATION -> paymentTime.receiptExpiration(
|
||||
subscriptionConfiguration.getBadgeExpiration(),
|
||||
subscriptionConfiguration.getBadgeGracePeriod());
|
||||
case BACKUP -> paymentTime.receiptExpiration(
|
||||
subscriptionConfiguration.getBackupExpiration(),
|
||||
subscriptionConfiguration.getBackupGracePeriod());
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
private String getSubscriptionTemplateId(long level, String currency, PaymentProvider processor) {
|
||||
final SubscriptionLevelConfiguration config = subscriptionConfiguration.getSubscriptionLevel(level);
|
||||
if (config == null) {
|
||||
@@ -854,13 +798,4 @@ public class SubscriptionController {
|
||||
SetSubscriptionLevelErrorResponse.Error.Type.UNSUPPORTED_CURRENCY, null))))
|
||||
.build()));
|
||||
}
|
||||
|
||||
@Nullable
|
||||
private static ClientPlatform getClientPlatform(@Nullable final String userAgentString) {
|
||||
try {
|
||||
return UserAgentUtil.parseUserAgentString(userAgentString).platform();
|
||||
} catch (final UnrecognizedUserAgentException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
+64
-115
@@ -59,8 +59,6 @@ import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CancellationException;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import org.apache.commons.lang3.Strings;
|
||||
import org.apache.http.HttpStatus;
|
||||
import org.slf4j.Logger;
|
||||
@@ -91,7 +89,6 @@ import org.whispersystems.textsecuregcm.registration.MessageTransport;
|
||||
import org.whispersystems.textsecuregcm.registration.RegistrationFraudException;
|
||||
import org.whispersystems.textsecuregcm.registration.RegistrationServiceClient;
|
||||
import org.whispersystems.textsecuregcm.registration.RegistrationServiceException;
|
||||
import org.whispersystems.textsecuregcm.registration.RegistrationServiceSenderException;
|
||||
import org.whispersystems.textsecuregcm.registration.TransportNotAllowedException;
|
||||
import org.whispersystems.textsecuregcm.registration.VerificationSession;
|
||||
import org.whispersystems.textsecuregcm.spam.RegistrationFraudChecker;
|
||||
@@ -105,7 +102,6 @@ import org.whispersystems.textsecuregcm.storage.VerificationSessionManager;
|
||||
import org.whispersystems.textsecuregcm.telephony.CarrierData;
|
||||
import org.whispersystems.textsecuregcm.telephony.CarrierDataException;
|
||||
import org.whispersystems.textsecuregcm.telephony.CarrierDataProvider;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.util.ObsoletePhoneNumberFormatException;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
@@ -225,27 +221,13 @@ public class VerificationController {
|
||||
maybeCarrierData = Optional.empty();
|
||||
}
|
||||
|
||||
final RegistrationServiceSession registrationServiceSession;
|
||||
try {
|
||||
final String sourceHost = (String) requestContext.getProperty(RemoteAddressFilter.REMOTE_ADDRESS_ATTRIBUTE_NAME);
|
||||
|
||||
registrationServiceSession = registrationServiceClient.createRegistrationSession(phoneNumber,
|
||||
sourceHost,
|
||||
accountsManager.getByE164(request.number()).isPresent(),
|
||||
maybeCarrierData.flatMap(CarrierData::mcc).orElse(null),
|
||||
maybeCarrierData.flatMap(CarrierData::mnc).orElse(null),
|
||||
REGISTRATION_RPC_TIMEOUT).join();
|
||||
} catch (final CancellationException e) {
|
||||
|
||||
throw new ServerErrorException("registration service unavailable", Response.Status.SERVICE_UNAVAILABLE);
|
||||
} catch (final CompletionException e) {
|
||||
|
||||
if (ExceptionUtils.unwrap(e) instanceof RateLimitExceededException re) {
|
||||
throw re;
|
||||
}
|
||||
|
||||
throw new ServerErrorException(Response.Status.INTERNAL_SERVER_ERROR, e);
|
||||
}
|
||||
final RegistrationServiceSession registrationServiceSession =
|
||||
registrationServiceClient.createRegistrationSession(phoneNumber,
|
||||
(String) requestContext.getProperty(RemoteAddressFilter.REMOTE_ADDRESS_ATTRIBUTE_NAME),
|
||||
accountsManager.getByE164(request.number()).isPresent(),
|
||||
maybeCarrierData.flatMap(CarrierData::mcc).orElse(null),
|
||||
maybeCarrierData.flatMap(CarrierData::mnc).orElse(null),
|
||||
REGISTRATION_RPC_TIMEOUT);
|
||||
|
||||
VerificationSession verificationSession = new VerificationSession(registrationServiceSession.encodedSessionId(),
|
||||
null,
|
||||
@@ -654,59 +636,44 @@ public class VerificationController {
|
||||
clientType,
|
||||
acceptLanguage.orElse(null),
|
||||
senderOverride,
|
||||
REGISTRATION_RPC_TIMEOUT).join();
|
||||
REGISTRATION_RPC_TIMEOUT);
|
||||
} catch (final VerificationSessionRateLimitExceededException e) {
|
||||
throw new ClientErrorException(buildResponseForRateLimitExceeded(verificationSession,
|
||||
e.getRegistrationSession(),
|
||||
e.getRetryDuration()));
|
||||
} catch (final RegistrationServiceException registrationServiceException) {
|
||||
throw registrationServiceException.getRegistrationSession()
|
||||
.map(s -> buildResponse(s, verificationSession))
|
||||
.map(verificationSessionResponse -> {
|
||||
final Response response = registrationServiceException instanceof TransportNotAllowedException
|
||||
? Response.status(418).entity(verificationSessionResponse).build()
|
||||
: Response.status(Response.Status.CONFLICT).entity(verificationSessionResponse).build();
|
||||
|
||||
accountsManager.getByE164(registrationServiceSession.number())
|
||||
.filter(existingAccount ->
|
||||
experimentEnrollmentManager.isEnrolled(existingAccount.getIdentifier(IdentityType.ACI), VERIFICATION_CODE_PUSH_NOTIFICATION_EXPERIMENT_NAME))
|
||||
.ifPresent(existingAccount -> {
|
||||
try {
|
||||
pushNotificationManager.sendVerificationCodeRequestedNotifications(existingAccount, clock.instant());
|
||||
} catch (final NotPushRegisteredException _) {
|
||||
}
|
||||
});
|
||||
} catch (final CancellationException e) {
|
||||
throw new ServerErrorException("registration service unavailable", Response.Status.SERVICE_UNAVAILABLE);
|
||||
} catch (final CompletionException e) {
|
||||
final Throwable unwrappedException = ExceptionUtils.unwrap(e);
|
||||
switch (unwrappedException) {
|
||||
case RateLimitExceededException rateLimitExceededException -> {
|
||||
if (rateLimitExceededException instanceof VerificationSessionRateLimitExceededException ve) {
|
||||
final Response response = buildResponseForRateLimitExceeded(verificationSession,
|
||||
ve.getRegistrationSession(),
|
||||
ve.getRetryDuration());
|
||||
throw new ClientErrorException(response);
|
||||
}
|
||||
|
||||
throw new RateLimitExceededException(rateLimitExceededException.getRetryDuration().orElse(null));
|
||||
}
|
||||
case RegistrationServiceException registrationServiceException ->
|
||||
throw registrationServiceException.getRegistrationSession()
|
||||
.map(s -> buildResponse(s, verificationSession))
|
||||
.map(verificationSessionResponse -> {
|
||||
final Response response = registrationServiceException instanceof TransportNotAllowedException
|
||||
? Response.status(418).entity(verificationSessionResponse).build()
|
||||
: Response.status(Response.Status.CONFLICT).entity(verificationSessionResponse).build();
|
||||
|
||||
return new ClientErrorException(response);
|
||||
})
|
||||
.orElseGet(NotFoundException::new);
|
||||
case RegistrationFraudException _ -> {
|
||||
if (dynamicConfigurationManager.getConfiguration().getRegistrationConfiguration()
|
||||
.squashDeclinedAttemptErrors()) {
|
||||
return buildResponse(registrationServiceSession, verificationSession);
|
||||
} else {
|
||||
throw unwrappedException.getCause();
|
||||
}
|
||||
}
|
||||
case RegistrationServiceSenderException _ -> throw unwrappedException;
|
||||
case null, default -> {
|
||||
logger.error("Registration service failure", unwrappedException);
|
||||
throw new ServerErrorException(Response.Status.INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
return new ClientErrorException(response);
|
||||
})
|
||||
.orElseGet(NotFoundException::new);
|
||||
} catch (final RegistrationFraudException e) {
|
||||
if (dynamicConfigurationManager.getConfiguration().getRegistrationConfiguration()
|
||||
.squashDeclinedAttemptErrors()) {
|
||||
return buildResponse(registrationServiceSession, verificationSession);
|
||||
} else {
|
||||
throw e.getCause();
|
||||
}
|
||||
} catch (final RuntimeException e) {
|
||||
logger.error("Registration service failure", e);
|
||||
throw new ServerErrorException(Response.Status.INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
|
||||
accountsManager.getByE164(registrationServiceSession.number())
|
||||
.filter(existingAccount ->
|
||||
experimentEnrollmentManager.isEnrolled(existingAccount.getIdentifier(IdentityType.ACI), VERIFICATION_CODE_PUSH_NOTIFICATION_EXPERIMENT_NAME))
|
||||
.ifPresent(existingAccount -> {
|
||||
try {
|
||||
pushNotificationManager.sendVerificationCodeRequestedNotifications(existingAccount, clock.instant());
|
||||
} catch (final NotPushRegisteredException _) {
|
||||
}
|
||||
});
|
||||
|
||||
Metrics.counter(CODE_REQUESTED_COUNTER_NAME, Tags.of(
|
||||
UserAgentTagUtil.getPlatformTag(userAgent),
|
||||
Tag.of(COUNTRY_CODE_TAG_NAME, Util.getCountryCode(registrationServiceSession.number())),
|
||||
@@ -746,8 +713,7 @@ public class VerificationController {
|
||||
schema = @Schema(implementation = Integer.class)))
|
||||
public VerificationSessionResponse verifyCode(@PathParam("sessionId") final String encodedSessionId,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
|
||||
@NotNull @Valid final SubmitVerificationCodeRequest submitVerificationCodeRequest)
|
||||
throws RateLimitExceededException {
|
||||
@NotNull @Valid final SubmitVerificationCodeRequest submitVerificationCodeRequest) {
|
||||
|
||||
final RegistrationServiceSession registrationServiceSession = retrieveRegistrationServiceSession(encodedSessionId);
|
||||
final VerificationSession verificationSession = retrieveVerificationSession(registrationServiceSession);
|
||||
@@ -764,35 +730,17 @@ public class VerificationController {
|
||||
try {
|
||||
resultSession = registrationServiceClient.checkVerificationCode(registrationServiceSession.id(),
|
||||
submitVerificationCodeRequest.code(),
|
||||
REGISTRATION_RPC_TIMEOUT)
|
||||
.join();
|
||||
} catch (final CancellationException e) {
|
||||
logger.warn("Unexpected cancellation from registration service", e);
|
||||
throw new ServerErrorException(Response.Status.SERVICE_UNAVAILABLE);
|
||||
} catch (final CompletionException e) {
|
||||
final Throwable unwrappedException = ExceptionUtils.unwrap(e);
|
||||
if (unwrappedException instanceof RateLimitExceededException rateLimitExceededException) {
|
||||
|
||||
if (rateLimitExceededException instanceof VerificationSessionRateLimitExceededException ve) {
|
||||
final Response response = buildResponseForRateLimitExceeded(verificationSession, ve.getRegistrationSession(),
|
||||
ve.getRetryDuration());
|
||||
throw new ClientErrorException(response);
|
||||
}
|
||||
|
||||
throw new RateLimitExceededException(rateLimitExceededException.getRetryDuration().orElse(null));
|
||||
|
||||
} else if (unwrappedException instanceof RegistrationServiceException registrationServiceException) {
|
||||
|
||||
throw registrationServiceException.getRegistrationSession()
|
||||
.map(s -> buildResponse(s, verificationSession))
|
||||
.map(verificationSessionResponse -> new ClientErrorException(
|
||||
Response.status(Response.Status.CONFLICT).entity(verificationSessionResponse).build()))
|
||||
.orElseGet(NotFoundException::new);
|
||||
|
||||
} else {
|
||||
logger.error("Registration service failure", unwrappedException);
|
||||
throw new ServerErrorException(Response.Status.INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
REGISTRATION_RPC_TIMEOUT);
|
||||
} catch (final VerificationSessionRateLimitExceededException e) {
|
||||
throw new ClientErrorException(buildResponseForRateLimitExceeded(verificationSession,
|
||||
e.getRegistrationSession(),
|
||||
e.getRetryDuration()));
|
||||
} catch (final RegistrationServiceException e) {
|
||||
throw e.getRegistrationSession()
|
||||
.map(s -> buildResponse(s, verificationSession))
|
||||
.map(verificationSessionResponse -> new ClientErrorException(
|
||||
Response.status(Response.Status.CONFLICT).entity(verificationSessionResponse).build()))
|
||||
.orElseGet(NotFoundException::new);
|
||||
}
|
||||
|
||||
boolean existingRRP = false;
|
||||
@@ -868,9 +816,8 @@ public class VerificationController {
|
||||
}
|
||||
|
||||
try {
|
||||
final RegistrationServiceSession registrationServiceSession = registrationServiceClient.getSession(sessionId,
|
||||
REGISTRATION_RPC_TIMEOUT).join()
|
||||
.orElseThrow(NotFoundException::new);
|
||||
final RegistrationServiceSession registrationServiceSession =
|
||||
registrationServiceClient.getSession(sessionId, REGISTRATION_RPC_TIMEOUT).orElseThrow(NotFoundException::new);
|
||||
|
||||
if (registrationServiceSession.verified()) {
|
||||
// Since there is a valid verification session we invalidate the other possible verification mechanism,
|
||||
@@ -882,14 +829,16 @@ public class VerificationController {
|
||||
|
||||
return registrationServiceSession;
|
||||
|
||||
} catch (final CompletionException | CancellationException e) {
|
||||
final Throwable unwrapped = ExceptionUtils.unwrap(e);
|
||||
|
||||
if (unwrapped instanceof StatusRuntimeException grpcRuntimeException) {
|
||||
if (grpcRuntimeException.getStatus().getCode() == Status.Code.INVALID_ARGUMENT) {
|
||||
throw new BadRequestException();
|
||||
}
|
||||
} catch (final StatusRuntimeException e) {
|
||||
if (e.getStatus().getCode() == Status.Code.INVALID_ARGUMENT) {
|
||||
throw new BadRequestException();
|
||||
}
|
||||
|
||||
logger.error("Registration service failure", e);
|
||||
throw new ServerErrorException(Response.Status.SERVICE_UNAVAILABLE, e);
|
||||
} catch (final WebApplicationException e) {
|
||||
throw e;
|
||||
} catch (final RuntimeException e) {
|
||||
logger.error("Registration service failure", e);
|
||||
throw new ServerErrorException(Response.Status.SERVICE_UNAVAILABLE, e);
|
||||
}
|
||||
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
|
||||
public record CreateDonationPermitResponse(
|
||||
@Schema(description = "A serialized DonationPermitResponse")
|
||||
@NotEmpty
|
||||
@NotNull
|
||||
@Valid
|
||||
byte[] permitResponse) {
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
|
||||
public record CreateDonationPermitsRequest(
|
||||
@Schema(description = "A serialized DonationPermitRequest")
|
||||
@NotEmpty
|
||||
@NotNull
|
||||
byte[] permitRequest) {
|
||||
}
|
||||
@@ -71,6 +71,10 @@ public class Experiment {
|
||||
this.experimentNullMismatchTimer = experimentNullMismatchTimer;
|
||||
}
|
||||
|
||||
public <T> void compareResult(final T expected, final T experimentResult) {
|
||||
recordResult(expected, experimentResult, Timer.start());
|
||||
}
|
||||
|
||||
public <T> void compareMonoResult(final T expected, final Mono<T> experimentMono) {
|
||||
final Timer.Sample sample = Timer.start();
|
||||
|
||||
|
||||
+47
-10
@@ -7,8 +7,9 @@ package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import java.security.SecureRandom;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
@@ -27,6 +28,8 @@ import org.signal.chat.account.DeleteUsernameLinkRequest;
|
||||
import org.signal.chat.account.DeleteUsernameLinkResponse;
|
||||
import org.signal.chat.account.GetAccountIdentityRequest;
|
||||
import org.signal.chat.account.GetAccountIdentityResponse;
|
||||
import org.signal.chat.account.GetEntitlementsRequest;
|
||||
import org.signal.chat.account.GetEntitlementsResponse;
|
||||
import org.signal.chat.account.ReserveUsernameHashRequest;
|
||||
import org.signal.chat.account.ReserveUsernameHashResponse;
|
||||
import org.signal.chat.account.SetDiscoverableByPhoneNumberRequest;
|
||||
@@ -44,11 +47,12 @@ import org.signal.chat.account.UsernameNotAvailable;
|
||||
import org.signal.chat.common.AccountIdentifiers;
|
||||
import org.signal.chat.errors.FailedPrecondition;
|
||||
import org.signal.libsignal.usernames.BaseUsernameException;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.ZkCredentialPublicKey;
|
||||
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
|
||||
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
|
||||
import org.whispersystems.textsecuregcm.controllers.AccountController;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
@@ -70,16 +74,19 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
|
||||
private final RateLimiters rateLimiters;
|
||||
private final UsernameHashZkProofVerifier usernameHashZkProofVerifier;
|
||||
private final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager;
|
||||
private final Clock clock;
|
||||
|
||||
public AccountsGrpcService(final AccountsManager accountsManager,
|
||||
final RateLimiters rateLimiters,
|
||||
final UsernameHashZkProofVerifier usernameHashZkProofVerifier,
|
||||
final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager) {
|
||||
final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager,
|
||||
final Clock clock) {
|
||||
|
||||
this.accountsManager = accountsManager;
|
||||
this.rateLimiters = rateLimiters;
|
||||
this.usernameHashZkProofVerifier = usernameHashZkProofVerifier;
|
||||
this.registrationRecoveryPasswordsManager = registrationRecoveryPasswordsManager;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -94,11 +101,41 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
|
||||
account.getUsernameHash().ifPresent(usernameHash ->
|
||||
accountIdentifiersBuilder.setUsernameHash(ByteString.copyFrom(usernameHash)));
|
||||
|
||||
if (account.getUsernameLinkHandle() != null) {
|
||||
accountIdentifiersBuilder.setUsernameLinkHandle(UUIDUtil.toByteString(account.getUsernameLinkHandle()));
|
||||
}
|
||||
|
||||
return GetAccountIdentityResponse.newBuilder()
|
||||
.setAccountIdentifiers(accountIdentifiersBuilder)
|
||||
.build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public GetEntitlementsResponse getEntitlements(final GetEntitlementsRequest request) {
|
||||
final Account account = getAuthenticatedAccount();
|
||||
final GetEntitlementsResponse.Builder builder = GetEntitlementsResponse.newBuilder();
|
||||
|
||||
final Instant now = clock.instant();
|
||||
|
||||
final Account.BackupVoucher backupVoucher = account.getBackupVoucher();
|
||||
if (backupVoucher != null && backupVoucher.expiration().isAfter(now)) {
|
||||
builder.setBackup(GetEntitlementsResponse.BackupEntitlement.newBuilder()
|
||||
.setExpirationEpochSeconds(backupVoucher.expiration().getEpochSecond())
|
||||
.setLevel(backupVoucher.receiptLevel()));
|
||||
}
|
||||
|
||||
builder.addAllBadges(account.getBadges().stream()
|
||||
.filter(badge -> badge.expiration().isAfter(now))
|
||||
.map(badge -> GetEntitlementsResponse.BadgeEntitlement.newBuilder()
|
||||
.setBadgeId(badge.id())
|
||||
.setExpirationEpochSeconds(badge.expiration().getEpochSecond())
|
||||
.setVisible(badge.visible())
|
||||
.build())
|
||||
.toList());
|
||||
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public DeleteAccountResponse deleteAccount(final DeleteAccountRequest request) {
|
||||
accountsManager.delete(AuthenticationUtil.requireAuthenticatedPrimaryDevice().accountIdentifier(),
|
||||
@@ -136,11 +173,6 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
|
||||
final List<byte[]> usernameHashes = new ArrayList<>(request.getUsernameHashesCount());
|
||||
|
||||
for (final ByteString usernameHash : request.getUsernameHashesList()) {
|
||||
if (usernameHash.size() != AccountController.USERNAME_HASH_LENGTH) {
|
||||
throw GrpcExceptions.fieldViolation("username_hashes",
|
||||
String.format("Username hash length must be %d bytes, but was actually %d",
|
||||
AccountController.USERNAME_HASH_LENGTH, usernameHash.size()));
|
||||
}
|
||||
usernameHashes.add(usernameHash.toByteArray());
|
||||
}
|
||||
|
||||
@@ -277,9 +309,14 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
|
||||
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
|
||||
|
||||
final Account authenticatedAccount = getAuthenticatedAccount();
|
||||
final byte[] zkCredentialKey = request.getPublicKey().toByteArray();
|
||||
final ZkCredentialPublicKey zkCredentialKey;
|
||||
try {
|
||||
zkCredentialKey = new ZkCredentialPublicKey(request.getPublicKey().toByteArray());
|
||||
} catch (InvalidInputException _) {
|
||||
throw GrpcExceptions.invalidArguments("invalid public key bytes");
|
||||
}
|
||||
|
||||
if (Arrays.equals(authenticatedAccount.getZkCredentialKey(), zkCredentialKey)) {
|
||||
if (authenticatedAccount.getZkCredentialKey().map(zkCredentialKey::equals).orElse(false)) {
|
||||
return SetZkCredentialKeyResponse.newBuilder()
|
||||
.setRotationId(Objects.requireNonNull(authenticatedAccount.getZkCredentialKeyRotationId()))
|
||||
.build();
|
||||
|
||||
+93
-1
@@ -6,10 +6,21 @@
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import java.security.SecureRandom;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.util.HexFormat;
|
||||
import java.util.Map;
|
||||
import java.util.stream.IntStream;
|
||||
import io.micrometer.core.instrument.DistributionSummary;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import org.signal.chat.attachments.GetStickerUploadFormRequest;
|
||||
import org.signal.chat.attachments.GetStickerUploadFormResponse;
|
||||
import org.signal.chat.attachments.GetUploadFormRequest;
|
||||
import org.signal.chat.attachments.GetUploadFormResponse;
|
||||
import org.signal.chat.attachments.SimpleAttachmentsGrpc;
|
||||
import org.signal.chat.common.S3UploadForm;
|
||||
import org.signal.chat.common.UploadForm;
|
||||
import org.signal.chat.errors.FailedPrecondition;
|
||||
import org.whispersystems.textsecuregcm.attachments.AttachmentGenerator;
|
||||
@@ -18,30 +29,51 @@ import org.whispersystems.textsecuregcm.attachments.GcsAttachmentGenerator;
|
||||
import org.whispersystems.textsecuregcm.attachments.TusAttachmentGenerator;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
|
||||
import org.whispersystems.textsecuregcm.controllers.AttachmentControllerV4;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.controllers.StickerController;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
|
||||
|
||||
public class AttachmentsGrpcService extends SimpleAttachmentsGrpc.AttachmentsImplBase {
|
||||
|
||||
private final ExperimentEnrollmentManager experimentEnrollmentManager;
|
||||
private final RateLimiter countRateLimiter;
|
||||
private final RateLimiter bytesRateLimiter;
|
||||
private final RateLimiter stickerPackLimiter;
|
||||
private final long maxUploadLength;
|
||||
private final Map<Integer, AttachmentGenerator> attachmentGenerators;
|
||||
private final PostPolicyGenerator stickerPolicyGenerator;
|
||||
private final Clock clock;
|
||||
private final SecureRandom secureRandom;
|
||||
|
||||
private static final S3UploadForm PROTOTYPE_STICKER_UPLOAD_FORM = S3UploadForm.newBuilder()
|
||||
.setAcl(PostPolicyGenerator.ACL)
|
||||
.setAlgorithm(PostPolicyGenerator.ALGORITHM)
|
||||
.build();
|
||||
|
||||
private static final String ATTACHMENT_SIZE_NAME =
|
||||
MetricsUtil.name(AttachmentsGrpcService.class, "attachmentSize");
|
||||
|
||||
public AttachmentsGrpcService(
|
||||
final ExperimentEnrollmentManager experimentEnrollmentManager,
|
||||
final RateLimiters rateLimiters,
|
||||
final GcsAttachmentGenerator gcsAttachmentGenerator,
|
||||
final TusAttachmentGenerator tusAttachmentGenerator,
|
||||
final long maxUploadLength) {
|
||||
final PostPolicyGenerator stickerPolicyGenerator,
|
||||
final long maxUploadLength,
|
||||
final Clock clock) {
|
||||
this.experimentEnrollmentManager = experimentEnrollmentManager;
|
||||
this.countRateLimiter = rateLimiters.getAttachmentLimiter();
|
||||
this.bytesRateLimiter = rateLimiters.getAttachmentBytesLimiter();
|
||||
this.stickerPackLimiter = rateLimiters.getStickerPackLimiter();
|
||||
this.stickerPolicyGenerator = stickerPolicyGenerator;
|
||||
this.maxUploadLength = maxUploadLength;
|
||||
this.clock = clock;
|
||||
this.secureRandom = new SecureRandom();
|
||||
this.attachmentGenerators = Map.of(
|
||||
2, gcsAttachmentGenerator,
|
||||
@@ -67,6 +99,11 @@ public class AttachmentsGrpcService extends SimpleAttachmentsGrpc.AttachmentsImp
|
||||
throw e;
|
||||
}
|
||||
|
||||
DistributionSummary.builder(ATTACHMENT_SIZE_NAME)
|
||||
.tags(Tags.of(UserAgentTagUtil.getPlatformTag(RequestAttributesUtil.getUserAgent().orElse(null))))
|
||||
.register(Metrics.globalRegistry)
|
||||
.record(request.getUploadLength());
|
||||
|
||||
final String key = AttachmentUtil.generateAttachmentKey(secureRandom);
|
||||
final boolean useCdn3 = this.experimentEnrollmentManager.isEnrolled(auth.accountIdentifier(),
|
||||
AttachmentUtil.CDN3_EXPERIMENT_NAME);
|
||||
@@ -80,4 +117,59 @@ public class AttachmentsGrpcService extends SimpleAttachmentsGrpc.AttachmentsImp
|
||||
.setSignedUploadLocation(descriptor.signedUploadLocation()))
|
||||
.build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public GetStickerUploadFormResponse getStickerUploadForm(final GetStickerUploadFormRequest request)
|
||||
throws RateLimitExceededException {
|
||||
|
||||
stickerPackLimiter.validate(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier());
|
||||
|
||||
final Instant currentTime = clock.instant();
|
||||
final String packId;
|
||||
{
|
||||
final byte[] packIdBytes = new byte[16];
|
||||
secureRandom.nextBytes(packIdBytes);
|
||||
|
||||
packId = HexFormat.of().formatHex(packIdBytes);
|
||||
}
|
||||
|
||||
final String packLocation = "stickers/" + packId;
|
||||
|
||||
final GetStickerUploadFormResponse.Builder responseBuilder = GetStickerUploadFormResponse.newBuilder()
|
||||
.setPackId(packId);
|
||||
|
||||
{
|
||||
final String manifestKey = packLocation + "/manifest.proto";
|
||||
|
||||
final PostPolicyGenerator.SignedPostPolicy manifestPolicy =
|
||||
stickerPolicyGenerator.createFor(manifestKey, StickerController.MAXIMUM_STICKER_MANIFEST_SIZE_BYTES, currentTime);
|
||||
|
||||
responseBuilder
|
||||
.setManifestUploadForm(PROTOTYPE_STICKER_UPLOAD_FORM.toBuilder()
|
||||
.setKey(manifestKey)
|
||||
.setCredential(manifestPolicy.credential())
|
||||
.setDate(manifestPolicy.formattedTimestamp())
|
||||
.setPolicy(manifestPolicy.encodedPolicy())
|
||||
.setSignature(manifestPolicy.signature())
|
||||
.build());
|
||||
}
|
||||
|
||||
IntStream.range(0, request.getStickerCount())
|
||||
.mapToObj(i -> {
|
||||
final String stickerKey = packLocation + "/full/" + i;
|
||||
final PostPolicyGenerator.SignedPostPolicy stickerPolicy =
|
||||
stickerPolicyGenerator.createFor(stickerKey, StickerController.MAXIMUM_STICKER_SIZE_BYTES, currentTime);
|
||||
|
||||
return PROTOTYPE_STICKER_UPLOAD_FORM.toBuilder()
|
||||
.setKey(stickerKey)
|
||||
.setCredential(stickerPolicy.credential())
|
||||
.setDate(stickerPolicy.formattedTimestamp())
|
||||
.setPolicy(stickerPolicy.encodedPolicy())
|
||||
.setSignature(stickerPolicy.signature())
|
||||
.build();
|
||||
})
|
||||
.forEach(responseBuilder::addStickerUploadForms);
|
||||
|
||||
return responseBuilder.build();
|
||||
}
|
||||
}
|
||||
+14
-21
@@ -8,6 +8,7 @@ import com.google.protobuf.ByteString;
|
||||
import com.google.protobuf.Empty;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.Flow;
|
||||
import org.signal.chat.backup.BackupStreamClosed;
|
||||
import org.signal.chat.backup.CopyMediaRequest;
|
||||
import org.signal.chat.backup.CopyMediaResponse;
|
||||
import org.signal.chat.backup.DeleteAllRequest;
|
||||
@@ -223,15 +224,16 @@ public class BackupsAnonymousGrpcService extends SimpleBackupsAnonymousGrpc.Back
|
||||
copyQuota = backupManager.getCopyQuota(backupUser,
|
||||
request.getItemsList().stream().map(item -> new CopyParameters(
|
||||
item.getSourceAttachmentCdn(), item.getSourceKey(),
|
||||
// uint32 in proto, make sure it fits in a signed int
|
||||
fromUnsignedExact(item.getObjectLength()),
|
||||
item.getObjectLength(),
|
||||
new MediaEncryptionParameters(item.getEncryptionKey().toByteArray(), item.getHmacKey().toByteArray()),
|
||||
item.getMediaId().toByteArray())).toList(), maxAttachmentSize);
|
||||
} catch (BackupFailedZkAuthenticationException e) {
|
||||
return JdkFlowAdapter.publisherToFlowPublisher(Mono.just(CopyMediaResponse
|
||||
.newBuilder()
|
||||
.setFailedAuthentication(FailedZkAuthentication.newBuilder().setDescription(e.getMessage()))
|
||||
.build()));
|
||||
return JdkFlowAdapter.publisherToFlowPublisher(
|
||||
Mono.error(GrpcExceptions.streamClosed(BackupStreamClosed.newBuilder()
|
||||
.setFailedAuthentication(FailedZkAuthentication.newBuilder()
|
||||
.setDescription(e.getMessage())
|
||||
.build())
|
||||
.build())));
|
||||
}
|
||||
return JdkFlowAdapter.publisherToFlowPublisher(backupManager.copyToBackup(copyQuota)
|
||||
.doOnNext(result -> backupMetrics.updateCopyCounter(
|
||||
@@ -308,10 +310,12 @@ public class BackupsAnonymousGrpcService extends SimpleBackupsAnonymousGrpc.Back
|
||||
.map(item -> new BackupManager.StorageDescriptor(item.getCdn(), item.getMediaId().toByteArray()))
|
||||
.toList());
|
||||
} catch (BackupFailedZkAuthenticationException e) {
|
||||
return JdkFlowAdapter.publisherToFlowPublisher(Mono.just(DeleteMediaResponse
|
||||
.newBuilder()
|
||||
.setFailedAuthentication(FailedZkAuthentication.newBuilder().setDescription(e.getMessage()))
|
||||
.build()));
|
||||
return JdkFlowAdapter.publisherToFlowPublisher(
|
||||
Mono.error(GrpcExceptions.streamClosed(BackupStreamClosed.newBuilder()
|
||||
.setFailedAuthentication(FailedZkAuthentication.newBuilder()
|
||||
.setDescription(e.getMessage())
|
||||
.build())
|
||||
.build())));
|
||||
}
|
||||
return JdkFlowAdapter.publisherToFlowPublisher(deleteItems
|
||||
.map(storageDescriptor -> DeleteMediaResponse.newBuilder()
|
||||
@@ -346,17 +350,6 @@ public class BackupsAnonymousGrpcService extends SimpleBackupsAnonymousGrpc.Back
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert an int from a proto uint32 to a signed positive integer, throwing if the value exceeds
|
||||
* {@link Integer#MAX_VALUE}. To convert to a long, see {@link Integer#toUnsignedLong(int)}
|
||||
*/
|
||||
private static int fromUnsignedExact(final int i) {
|
||||
if (i < 0) {
|
||||
throw GrpcExceptions.invalidArguments("integer length too large");
|
||||
}
|
||||
return i;
|
||||
}
|
||||
|
||||
private interface Deserializer<T> {
|
||||
|
||||
T deserialize(byte[] bytes) throws InvalidInputException, InvalidKeyException;
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import org.signal.chat.common.Badge;
|
||||
import org.signal.chat.common.BadgeSvg;
|
||||
|
||||
public class BadgeGrpcHelper {
|
||||
|
||||
public static Badge toGrpcBadge(final org.whispersystems.textsecuregcm.entities.Badge badge) {
|
||||
final Badge.Builder builder = Badge.newBuilder()
|
||||
.setId(badge.getId())
|
||||
.setCategory(badge.getCategory())
|
||||
.setName(badge.getName())
|
||||
.setDescription(badge.getDescription())
|
||||
.addAllSprites6(badge.getSprites6())
|
||||
.setSvg(badge.getSvg());
|
||||
|
||||
badge.getSvgs().stream()
|
||||
.map(badgeSvg -> BadgeSvg.newBuilder()
|
||||
.setDark(badgeSvg.getDark())
|
||||
.setLight(badgeSvg.getLight())
|
||||
.build())
|
||||
.forEach(builder::addSvgs);
|
||||
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
}
|
||||
+32
@@ -8,8 +8,12 @@ package org.whispersystems.textsecuregcm.grpc;
|
||||
import com.google.protobuf.ByteString;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import org.signal.chat.credentials.ExternalServiceType;
|
||||
import org.signal.chat.credentials.GetCreateCallLinkCredentialsRequest;
|
||||
import org.signal.chat.credentials.GetCreateCallLinkCredentialsResponse;
|
||||
import org.signal.chat.credentials.GetDeliveryCertificateRequest;
|
||||
import org.signal.chat.credentials.GetDeliveryCertificateResponse;
|
||||
import org.signal.chat.credentials.GetExternalServiceCredentialsRequest;
|
||||
@@ -19,8 +23,10 @@ import org.signal.chat.credentials.GetGroupCredentialsResponse;
|
||||
import org.signal.chat.credentials.SimpleCredentialsGrpc;
|
||||
import org.signal.libsignal.protocol.ServiceId;
|
||||
import org.signal.libsignal.zkgroup.GenericServerSecretParams;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.auth.ServerZkAuthOperations;
|
||||
import org.signal.libsignal.zkgroup.calllinks.CallLinkAuthCredentialResponse;
|
||||
import org.signal.libsignal.zkgroup.calllinks.CreateCallLinkCredentialRequest;
|
||||
import org.whispersystems.textsecuregcm.auth.CertificateGenerator;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
|
||||
@@ -133,4 +139,30 @@ public class CredentialsGrpcService extends SimpleCredentialsGrpc.CredentialsImp
|
||||
|
||||
return responseBuilder.build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public GetCreateCallLinkCredentialsResponse getCreateCallLinkCredentials(final GetCreateCallLinkCredentialsRequest request)
|
||||
throws RateLimitExceededException {
|
||||
|
||||
final UUID accountIdentifier = AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier();
|
||||
rateLimiters.getCreateCallLinkLimiter().validate(accountIdentifier);
|
||||
|
||||
final Instant truncatedDayTimestamp = clock.instant().truncatedTo(ChronoUnit.DAYS);
|
||||
|
||||
try {
|
||||
final CreateCallLinkCredentialRequest createCallLinkCredentialRequest =
|
||||
new CreateCallLinkCredentialRequest(request.getCredentialRequest().toByteArray());
|
||||
|
||||
return GetCreateCallLinkCredentialsResponse.newBuilder()
|
||||
.setRedemptionTimeSeconds(truncatedDayTimestamp.getEpochSecond())
|
||||
.setCredential(ByteString.copyFrom(createCallLinkCredentialRequest.issueCredential(
|
||||
new ServiceId.Aci(accountIdentifier),
|
||||
truncatedDayTimestamp,
|
||||
serverSecretParams)
|
||||
.serialize()))
|
||||
.build();
|
||||
} catch (final InvalidInputException e) {
|
||||
throw GrpcExceptions.invalidArguments("Invalid 'create call link credential' request");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -138,7 +138,9 @@ public class DevicesGrpcService extends SimpleDevicesGrpc.DevicesImplBase {
|
||||
final Device device = account.getDevice(authenticatedDevice.deviceId())
|
||||
.orElseThrow(() -> GrpcExceptions.invalidCredentials("invalid credentials"));
|
||||
|
||||
if (!Objects.equals(device.getApnId(), apnsToken) || !Objects.equals(device.getGcmId(), fcmToken)) {
|
||||
// Unlike FCM tokens, we need current "last updated" timestamps for APNs tokens and so update device records
|
||||
// unconditionally if it's an APNS request
|
||||
if (request.hasApnsTokenRequest() || !Objects.equals(device.getGcmId(), fcmToken)) {
|
||||
accountsManager.updateDevice(account.getIdentifier(IdentityType.ACI), authenticatedDevice.deviceId(), d -> {
|
||||
d.setApnId(apnsToken);
|
||||
d.setGcmId(fcmToken);
|
||||
|
||||
+33
-1
@@ -1,8 +1,11 @@
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import com.google.protobuf.Empty;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import org.signal.chat.donations.CreateDonationPermitRequest;
|
||||
import org.signal.chat.donations.CreateDonationPermitResponse;
|
||||
import org.signal.chat.donations.RedeemReceiptRequest;
|
||||
import org.signal.chat.donations.RedeemReceiptResponse;
|
||||
import org.signal.chat.donations.SimpleDonationsGrpc;
|
||||
@@ -10,6 +13,8 @@ import org.signal.chat.errors.FailedPrecondition;
|
||||
import org.signal.chat.errors.FailedZkAuthentication;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.VerificationFailedException;
|
||||
import org.signal.libsignal.zkgroup.donation.DonationPermitRequest;
|
||||
import org.signal.libsignal.zkgroup.donation.DonationPermitResponse;
|
||||
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialPresentation;
|
||||
import org.signal.libsignal.zkgroup.receipts.ReceiptSerial;
|
||||
import org.signal.libsignal.zkgroup.receipts.ServerZkReceiptOperations;
|
||||
@@ -18,8 +23,10 @@ import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
|
||||
import org.whispersystems.textsecuregcm.configuration.BadgesConfiguration;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountBadge;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.DonationPermitsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.RedeemedReceiptsManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.ReceiptCredentialPresentationFactory;
|
||||
|
||||
@@ -31,6 +38,8 @@ public class DonationsGrpcService extends SimpleDonationsGrpc.DonationsImplBase
|
||||
private final AccountsManager accountsManager;
|
||||
private final BadgesConfiguration badgesConfiguration;
|
||||
private final ReceiptCredentialPresentationFactory receiptCredentialPresentationFactory;
|
||||
private final DonationPermitsManager donationPermitsManager;
|
||||
private final RateLimiters rateLimiters;
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(DonationsGrpcService.class);
|
||||
|
||||
@@ -40,7 +49,9 @@ public class DonationsGrpcService extends SimpleDonationsGrpc.DonationsImplBase
|
||||
final RedeemedReceiptsManager redeemedReceiptsManager,
|
||||
final AccountsManager accountsManager,
|
||||
final BadgesConfiguration badgesConfiguration,
|
||||
final ReceiptCredentialPresentationFactory receiptCredentialPresentationFactory) {
|
||||
final ReceiptCredentialPresentationFactory receiptCredentialPresentationFactory,
|
||||
final DonationPermitsManager donationPermitsManager,
|
||||
final RateLimiters rateLimiters) {
|
||||
|
||||
this.clock = clock;
|
||||
this.serverZkReceiptOperations = serverZkReceiptOperations;
|
||||
@@ -48,6 +59,8 @@ public class DonationsGrpcService extends SimpleDonationsGrpc.DonationsImplBase
|
||||
this.accountsManager = accountsManager;
|
||||
this.badgesConfiguration = badgesConfiguration;
|
||||
this.receiptCredentialPresentationFactory = receiptCredentialPresentationFactory;
|
||||
this.donationPermitsManager = donationPermitsManager;
|
||||
this.rateLimiters = rateLimiters;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -101,4 +114,23 @@ public class DonationsGrpcService extends SimpleDonationsGrpc.DonationsImplBase
|
||||
.build();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public CreateDonationPermitResponse createDonationPermit(final CreateDonationPermitRequest request) throws Exception {
|
||||
final DonationPermitRequest permitRequest;
|
||||
try {
|
||||
permitRequest = new DonationPermitRequest(request.getDonationPermitRequest().toByteArray());
|
||||
} catch (InvalidInputException e) {
|
||||
throw GrpcExceptions.invalidArguments("invalid permit request");
|
||||
}
|
||||
|
||||
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
|
||||
rateLimiters.getCreateDonationPermitLimiter().validate(authenticatedDevice.accountIdentifier(), permitRequest.getPermitCount());
|
||||
|
||||
final DonationPermitResponse permitResponse = donationPermitsManager.issue(permitRequest);
|
||||
|
||||
return CreateDonationPermitResponse.newBuilder()
|
||||
.setDonationPermitResponse(ByteString.copyFrom(permitResponse.serialize()))
|
||||
.build();
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -39,7 +39,7 @@ public class ErrorConformanceInterceptor implements ServerInterceptor {
|
||||
}
|
||||
|
||||
switch (status.getCode()) {
|
||||
case UNAUTHENTICATED, UNAVAILABLE, INVALID_ARGUMENT, RESOURCE_EXHAUSTED -> {
|
||||
case UNAUTHENTICATED, UNAVAILABLE, INVALID_ARGUMENT, RESOURCE_EXHAUSTED, ABORTED -> {
|
||||
}
|
||||
default -> {
|
||||
log.error("Intercepted call {} returned illegal application status {}: {}",
|
||||
|
||||
@@ -39,6 +39,11 @@ public class GrpcExceptions {
|
||||
.setReason("BAD_AUTHENTICATION")
|
||||
.build());
|
||||
|
||||
private static final Any ERROR_INFO_STREAM_CLOSED = Any.pack(ErrorInfo.newBuilder()
|
||||
.setDomain(DOMAIN)
|
||||
.setReason("STREAM_CLOSED")
|
||||
.build());
|
||||
|
||||
private static final com.google.rpc.Status UPGRADE_REQUIRED = com.google.rpc.Status.newBuilder()
|
||||
.setCode(Status.Code.INVALID_ARGUMENT.value())
|
||||
.setMessage("Upgrade required")
|
||||
@@ -144,6 +149,20 @@ public class GrpcExceptions {
|
||||
return StatusProto.toStatusRuntimeException(builder.build());
|
||||
}
|
||||
|
||||
/// The server terminated the stream non-successfully for a reason specific to the RPC. The server must provide
|
||||
/// additional information about the stream closure reason via the `streamClosedMessage`.
|
||||
///
|
||||
/// @param streamClosedMessage The additional domain-specific proto message that indicates the closure reason
|
||||
/// @return A [StatusRuntimeException] encoding the error
|
||||
public static <T extends com.google.protobuf.Message> StatusRuntimeException streamClosed(
|
||||
final T streamClosedMessage) {
|
||||
return StatusProto.toStatusRuntimeException(com.google.rpc.Status.newBuilder()
|
||||
.setCode(Status.Code.ABORTED.value())
|
||||
.addDetails(ERROR_INFO_STREAM_CLOSED)
|
||||
.addDetails(Any.pack(streamClosedMessage))
|
||||
.build());
|
||||
}
|
||||
|
||||
public static StatusRuntimeException unavailable() {
|
||||
return unavailable(null);
|
||||
}
|
||||
|
||||
+19
-68
@@ -15,8 +15,10 @@ import org.signal.keytransparency.client.E164MonitorRequest;
|
||||
import org.signal.keytransparency.client.E164SearchRequest;
|
||||
import org.signal.keytransparency.client.MonitorRequest;
|
||||
import org.signal.keytransparency.client.MonitorResponse;
|
||||
import org.signal.keytransparency.client.MonitorResponseV2;
|
||||
import org.signal.keytransparency.client.SearchRequest;
|
||||
import org.signal.keytransparency.client.SearchResponse;
|
||||
import org.signal.keytransparency.client.SearchResponseV2;
|
||||
import org.signal.keytransparency.client.SimpleKeyTransparencyQueryServiceGrpc;
|
||||
import org.signal.keytransparency.client.UsernameHashMonitorRequest;
|
||||
import org.whispersystems.textsecuregcm.controllers.AccountController;
|
||||
@@ -39,102 +41,51 @@ public class KeyTransparencyGrpcService extends
|
||||
}
|
||||
|
||||
@Override
|
||||
public SearchResponse search(final SearchRequest request) throws RateLimitExceededException {
|
||||
public SearchResponseV2 searchV2(final SearchRequest request) throws RateLimitExceededException {
|
||||
rateLimiters.getKeyTransparencySearchLimiter().validate(RequestAttributesUtil.getRemoteAddress().getHostAddress());
|
||||
return client.search(validateSearchRequest(request));
|
||||
}
|
||||
|
||||
@Override
|
||||
public MonitorResponse monitor(final MonitorRequest request) throws RateLimitExceededException {
|
||||
public MonitorResponseV2 monitorV2(final MonitorRequest request) throws RateLimitExceededException {
|
||||
rateLimiters.getKeyTransparencyMonitorLimiter().validate(RequestAttributesUtil.getRemoteAddress().getHostAddress());
|
||||
return client.monitor(validateMonitorRequest(request));
|
||||
}
|
||||
|
||||
@Override
|
||||
public DistinguishedResponse distinguished(final DistinguishedRequest request) throws RateLimitExceededException {
|
||||
public DistinguishedResponse distinguishedV2(final DistinguishedRequest request) throws RateLimitExceededException {
|
||||
rateLimiters.getKeyTransparencyDistinguishedLimiter().validate(RequestAttributesUtil.getRemoteAddress().getHostAddress());
|
||||
// A client's very first distinguished request will not have a "last" parameter
|
||||
if (request.hasLast() && request.getLast() <= 0) {
|
||||
throw Status.INVALID_ARGUMENT.withDescription("Last tree head size must be positive").asRuntimeException();
|
||||
}
|
||||
return client.distinguished(request);
|
||||
}
|
||||
|
||||
private SearchRequest validateSearchRequest(final SearchRequest request) {
|
||||
validateAci(request.getAci().toByteArray());
|
||||
|
||||
if (request.hasE164SearchRequest()) {
|
||||
final E164SearchRequest e164SearchRequest = request.getE164SearchRequest();
|
||||
if (e164SearchRequest.getUnidentifiedAccessKey().isEmpty() != e164SearchRequest.getE164().isEmpty()) {
|
||||
throw Status.INVALID_ARGUMENT.withDescription("Unidentified access key and E164 must be provided together or not at all").asRuntimeException();
|
||||
throw GrpcExceptions.fieldViolation("e164_search_request", "Unidentified access key and E164 must be provided together or not at all");
|
||||
}
|
||||
}
|
||||
|
||||
if (!request.getConsistency().hasDistinguished()) {
|
||||
throw Status.INVALID_ARGUMENT.withDescription("Must provide distinguished tree head size").asRuntimeException();
|
||||
}
|
||||
|
||||
validateConsistencyParameters(request.getConsistency());
|
||||
return request;
|
||||
}
|
||||
|
||||
private void validateAci(final byte[] aci) {
|
||||
try {
|
||||
AciServiceIdentifier.fromBytes(aci);
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw GrpcExceptions.fieldViolation("aci", "Invalid ACI");
|
||||
}
|
||||
}
|
||||
|
||||
private MonitorRequest validateMonitorRequest(final MonitorRequest request) {
|
||||
final AciMonitorRequest aciMonitorRequest = request.getAci();
|
||||
validateAci(request.getAci().getAci().toByteArray());
|
||||
|
||||
try {
|
||||
AciServiceIdentifier.fromBytes(aciMonitorRequest.getAci().toByteArray());
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw Status.INVALID_ARGUMENT.withDescription("Invalid ACI").asRuntimeException();
|
||||
}
|
||||
if (aciMonitorRequest.getEntryPosition() <= 0) {
|
||||
throw Status.INVALID_ARGUMENT.withDescription("Aci entry position must be positive").asRuntimeException();
|
||||
}
|
||||
if (aciMonitorRequest.getCommitmentIndex().size() != COMMITMENT_INDEX_LENGTH) {
|
||||
throw Status.INVALID_ARGUMENT.withDescription("Aci commitment index must be 32 bytes").asRuntimeException();
|
||||
if (!request.getConsistency().hasLast()) {
|
||||
throw GrpcExceptions.fieldViolation("consistency_last", "Must provide distinguished and last tree head sizes");
|
||||
}
|
||||
|
||||
if (request.hasUsernameHash()) {
|
||||
final UsernameHashMonitorRequest usernameHashMonitorRequest = request.getUsernameHash();
|
||||
if (usernameHashMonitorRequest.getUsernameHash().isEmpty()) {
|
||||
throw Status.INVALID_ARGUMENT.withDescription("Username hash cannot be empty").asRuntimeException();
|
||||
}
|
||||
if (usernameHashMonitorRequest.getUsernameHash().size() != AccountController.USERNAME_HASH_LENGTH) {
|
||||
throw Status.INVALID_ARGUMENT.withDescription("Invalid username hash length").asRuntimeException();
|
||||
}
|
||||
if (usernameHashMonitorRequest.getEntryPosition() <= 0) {
|
||||
throw Status.INVALID_ARGUMENT.withDescription("Username hash entry position must be positive").asRuntimeException();
|
||||
}
|
||||
if (usernameHashMonitorRequest.getCommitmentIndex().size() != COMMITMENT_INDEX_LENGTH) {
|
||||
throw Status.INVALID_ARGUMENT.withDescription("Username hash commitment index must be 32 bytes").asRuntimeException();
|
||||
}
|
||||
}
|
||||
|
||||
if (request.hasE164()) {
|
||||
final E164MonitorRequest e164MonitorRequest = request.getE164();
|
||||
if (e164MonitorRequest.getE164().isEmpty()) {
|
||||
throw Status.INVALID_ARGUMENT.withDescription("E164 cannot be empty").asRuntimeException();
|
||||
}
|
||||
if (e164MonitorRequest.getEntryPosition() <= 0) {
|
||||
throw Status.INVALID_ARGUMENT.withDescription("E164 entry position must be positive").asRuntimeException();
|
||||
}
|
||||
if (e164MonitorRequest.getCommitmentIndex().size() != COMMITMENT_INDEX_LENGTH) {
|
||||
throw Status.INVALID_ARGUMENT.withDescription("E164 commitment index must be 32 bytes").asRuntimeException();
|
||||
}
|
||||
}
|
||||
|
||||
if (!request.getConsistency().hasDistinguished() || !request.getConsistency().hasLast()) {
|
||||
throw Status.INVALID_ARGUMENT.withDescription("Must provide distinguished and last tree head sizes").asRuntimeException();
|
||||
}
|
||||
|
||||
validateConsistencyParameters(request.getConsistency());
|
||||
return request;
|
||||
}
|
||||
|
||||
private static void validateConsistencyParameters(final ConsistencyParameters consistency) {
|
||||
if (consistency.getDistinguished() <= 0) {
|
||||
throw Status.INVALID_ARGUMENT.withDescription("Distinguished tree head size must be positive").asRuntimeException();
|
||||
}
|
||||
|
||||
if (consistency.hasLast() && consistency.getLast() <= 0) {
|
||||
throw Status.INVALID_ARGUMENT.withDescription("Last tree head size must be positive").asRuntimeException();
|
||||
}
|
||||
}
|
||||
}
|
||||
+21
-26
@@ -6,11 +6,13 @@ package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.protobuf.Empty;
|
||||
import io.grpc.StatusRuntimeException;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.time.Duration;
|
||||
import java.util.UUID;
|
||||
import javax.annotation.Nullable;
|
||||
import org.signal.chat.messages.GetMessagesResponse;
|
||||
import org.signal.chat.messages.GetMessagesStreamClosed;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.DisconnectionRequestListener;
|
||||
@@ -54,14 +56,10 @@ public class MessageDispatcher {
|
||||
|
||||
public static final GetMessagesResponse QUEUE_EMPTY_RESPONSE =
|
||||
GetMessagesResponse.newBuilder().setQueueEmpty(Empty.getDefaultInstance()).build();
|
||||
private static final GetMessagesResponse CONFLICTING_STREAM_RESPONSE = GetMessagesResponse.newBuilder()
|
||||
.setTerminated(GetMessagesResponse.Terminated.newBuilder()
|
||||
.setConflictingStream(Empty.getDefaultInstance()))
|
||||
.build();
|
||||
private static final GetMessagesResponse REAUTHENTICATION_REQUIRED_RESPONSE = GetMessagesResponse.newBuilder()
|
||||
.setTerminated(GetMessagesResponse.Terminated.newBuilder()
|
||||
.setReauthenticationRequired(Empty.getDefaultInstance()))
|
||||
.build();
|
||||
private static final StatusRuntimeException CONFLICTING_STREAM_EXCEPTION =
|
||||
GrpcExceptions.streamClosed(GetMessagesStreamClosed.newBuilder()
|
||||
.setConflictingStream(Empty.getDefaultInstance())
|
||||
.build());
|
||||
|
||||
private static final String SEND_MESSAGES_FLUX_NAME = MetricsUtil.name(MessageDispatcher.class, "sendMessages");
|
||||
|
||||
@@ -99,8 +97,8 @@ public class MessageDispatcher {
|
||||
/// terminates for any reason. The error from the client will be propagated to the returned flux. The stream may also
|
||||
/// terminate with any other error encountered retrieving messages or processing acknowledgements.
|
||||
///
|
||||
/// The returned flux will emit a [GetMessagesResponse.Terminated] and then complete if
|
||||
/// - A disconnection request (typically indicating a change in authorization credentials) is received.
|
||||
/// The returned flux will error with a [GrpcExceptions#streamClosed] non-ok status exception if:
|
||||
/// - A disconnection request (typically indicating a change in authorization credentials) is received
|
||||
/// - A client requests messages for the same account/device while this stream is still active
|
||||
///
|
||||
/// When the stream terminates for any reason and the client has messages remaining in their queue, a push
|
||||
@@ -167,7 +165,11 @@ public class MessageDispatcher {
|
||||
pendingAcknowledgementTracker.markEndOfQueue();
|
||||
yield Mono.empty();
|
||||
}
|
||||
}, MAX_UNACKED_MESSAGES);
|
||||
}, MAX_UNACKED_MESSAGES)
|
||||
.onErrorMap(ConflictingMessageConsumerException.class, _ -> {
|
||||
messageMetrics.measureMessageStreamDisplaced(MessageMetrics.GRPC_CHANNEL, userAgent, true);
|
||||
return CONFLICTING_STREAM_EXCEPTION;
|
||||
});
|
||||
|
||||
// Only emit envelopes when the permit flux emits a value. Initially it is seeded MAX_UNACKED_MESSAGES permits,
|
||||
// after that a permit is emitted every time we receive an ack.
|
||||
@@ -204,18 +206,8 @@ public class MessageDispatcher {
|
||||
ackCompletions,
|
||||
// Emits a queue empty once all messages prior to the queueEmpty signal have been acked
|
||||
pendingAcknowledgementTracker.queueDrained(),
|
||||
// Emit a Terminated response if we receive a disconnection request
|
||||
disconnectionSignal(account, device))
|
||||
.onErrorResume(ConflictingMessageConsumerException.class, _ -> Mono.just(CONFLICTING_STREAM_RESPONSE))
|
||||
.takeUntil(response -> switch (response.getResponseCase()) {
|
||||
case ENVELOPE, QUEUE_EMPTY -> false;
|
||||
case TERMINATED -> {
|
||||
messageMetrics.measureMessageStreamDisplaced(MessageMetrics.GRPC_CHANNEL, userAgent,
|
||||
response.getTerminated().hasConflictingStream());
|
||||
yield true;
|
||||
}
|
||||
case RESPONSE_NOT_SET -> throw new IllegalStateException("tried to return an invalid GetMessagesResponse");
|
||||
})
|
||||
// Emit an invalid credentials error if we receive a disconnection request
|
||||
disconnectionSignal(account, device, userAgent))
|
||||
.doFinally(_ -> maybeSchedulePush(account, device));
|
||||
}
|
||||
|
||||
@@ -232,11 +224,14 @@ public class MessageDispatcher {
|
||||
|
||||
/// Watch for a disconnection signal from the [DisconnectionRequestManager]
|
||||
///
|
||||
/// @return Mono that completes with a [org.signal.chat.messages.GetMessagesResponse.Terminated] response if the
|
||||
/// @return Mono that completes with an `InvalidCredentials` status if the
|
||||
/// device receives a disconnection request
|
||||
private Mono<GetMessagesResponse> disconnectionSignal(final Account account, final Device device) {
|
||||
private Mono<GetMessagesResponse> disconnectionSignal(final Account account, final Device device, final UserAgent userAgent) {
|
||||
return Mono.create(sink -> {
|
||||
final DisconnectionRequestListener listener = () -> sink.success(REAUTHENTICATION_REQUIRED_RESPONSE);
|
||||
final DisconnectionRequestListener listener = () -> {
|
||||
messageMetrics.measureMessageStreamDisplaced(MessageMetrics.GRPC_CHANNEL, userAgent, false);
|
||||
sink.error(GrpcExceptions.invalidCredentials("reauthentication required"));
|
||||
};
|
||||
disconnectionRequestManager.addListener(account.getUuid(), device.getId(), listener);
|
||||
sink.onDispose(() -> disconnectionRequestManager.removeListener(account.getUuid(), device.getId(), listener));
|
||||
});
|
||||
|
||||
+12
@@ -30,6 +30,7 @@ import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.atomic.LongAdder;
|
||||
import javax.annotation.Nullable;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
@@ -65,12 +66,19 @@ public class MetricServerInterceptor implements ServerInterceptor {
|
||||
@VisibleForTesting
|
||||
static final String DURATION_TIMER_NAME = MetricsUtil.name(MetricServerInterceptor.class, "processingDuration");
|
||||
|
||||
private static final String ACTIVE_REQUESTS_GAUGE_NAME =
|
||||
MetricsUtil.name(MetricServerInterceptor.class, "activeRequests");
|
||||
|
||||
private final MeterRegistry meterRegistry;
|
||||
private final ClientReleaseManager clientReleaseManager;
|
||||
|
||||
private final LongAdder activeRequests;
|
||||
|
||||
public MetricServerInterceptor(final MeterRegistry meterRegistry, final ClientReleaseManager clientReleaseManager) {
|
||||
this.meterRegistry = meterRegistry;
|
||||
this.clientReleaseManager = clientReleaseManager;
|
||||
|
||||
this.activeRequests = meterRegistry.gauge(ACTIVE_REQUESTS_GAUGE_NAME, new LongAdder());
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -194,6 +202,8 @@ public class MetricServerInterceptor implements ServerInterceptor {
|
||||
this.requestBytesCounter = meterRegistry.counter(REQUEST_BYTES_COUNTER_NAME, tags);
|
||||
this.responseTimer = meterRegistry.timer(DURATION_TIMER_NAME, tags);
|
||||
this.sample = Timer.start(meterRegistry);
|
||||
|
||||
activeRequests.increment();
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -210,12 +220,14 @@ public class MetricServerInterceptor implements ServerInterceptor {
|
||||
@Override
|
||||
public void onComplete() {
|
||||
this.sample.stop(responseTimer);
|
||||
activeRequests.decrement();
|
||||
super.onComplete();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCancel() {
|
||||
this.sample.stop(responseTimer);
|
||||
activeRequests.decrement();
|
||||
super.onCancel();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.CustomerAwareSubscriptionPaymentProcessor;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PayPalDonationsTranslator;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentDetails;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentMethod;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionCurrencyUtil;
|
||||
|
||||
public class OneTimeDonationUtil {
|
||||
|
||||
private static final String EURO_CURRENCY_CODE = "EUR";
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(OneTimeDonationUtil.class);
|
||||
|
||||
/// Thrown if a one time donation level cannot be parsed or if it is not found in configuration
|
||||
public static class InvalidLevelException extends Exception {
|
||||
|
||||
public InvalidLevelException(final String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
public record LocalizedPayPalDonationLineItem(Locale locale, String itemName){}
|
||||
public record DonationLevelDetails(long level, Duration levelExpiration){}
|
||||
|
||||
public sealed interface OneTimeDonationRequestValidationResult permits OneTimeDonationRequestValidationResult.Success,
|
||||
OneTimeDonationRequestValidationResult.UnsupportedCurrency,
|
||||
OneTimeDonationRequestValidationResult.UnsupportedLevel,
|
||||
OneTimeDonationRequestValidationResult.AmountBelowMinimum,
|
||||
OneTimeDonationRequestValidationResult.AmountAboveSepaLimit {
|
||||
|
||||
record Success() implements OneTimeDonationRequestValidationResult {}
|
||||
|
||||
record UnsupportedCurrency() implements OneTimeDonationRequestValidationResult {}
|
||||
|
||||
record UnsupportedLevel() implements OneTimeDonationRequestValidationResult {}
|
||||
|
||||
record AmountBelowMinimum(BigDecimal minimum) implements OneTimeDonationRequestValidationResult {}
|
||||
|
||||
record AmountAboveSepaLimit(BigDecimal maximum) implements OneTimeDonationRequestValidationResult {}
|
||||
|
||||
}
|
||||
|
||||
public static OneTimeDonationRequestValidationResult validateOneTimeDonationRequest(
|
||||
final String currency,
|
||||
final BigDecimal amount,
|
||||
final long level,
|
||||
final PaymentMethod paymentMethod,
|
||||
final OneTimeDonationConfiguration oneTimeDonationConfiguration,
|
||||
final CustomerAwareSubscriptionPaymentProcessor manager
|
||||
) {
|
||||
|
||||
if (!(level == oneTimeDonationConfiguration.gift().level()
|
||||
|| level == oneTimeDonationConfiguration.boost().level())) {
|
||||
return new OneTimeDonationRequestValidationResult.UnsupportedLevel();
|
||||
}
|
||||
|
||||
if (!manager.getSupportedCurrenciesForPaymentMethod(paymentMethod)
|
||||
.contains(currency.toLowerCase(Locale.ROOT))) {
|
||||
return new OneTimeDonationRequestValidationResult.UnsupportedCurrency();
|
||||
}
|
||||
|
||||
final BigDecimal minCurrencyAmountMajorUnits = oneTimeDonationConfiguration.currencies()
|
||||
.get(currency.toLowerCase(Locale.ROOT)).minimum();
|
||||
final BigDecimal minCurrencyAmountMinorUnits = SubscriptionCurrencyUtil.convertConfiguredAmountToApiAmount(
|
||||
currency,
|
||||
minCurrencyAmountMajorUnits);
|
||||
if (minCurrencyAmountMinorUnits.compareTo(amount) > 0) {
|
||||
return new OneTimeDonationRequestValidationResult.AmountBelowMinimum(minCurrencyAmountMajorUnits);
|
||||
}
|
||||
|
||||
if (paymentMethod == PaymentMethod.SEPA_DEBIT &&
|
||||
amount.compareTo(SubscriptionCurrencyUtil.convertConfiguredAmountToApiAmount(
|
||||
EURO_CURRENCY_CODE,
|
||||
oneTimeDonationConfiguration.sepaMaximumEuros())) > 0) {
|
||||
return new OneTimeDonationRequestValidationResult.AmountAboveSepaLimit(
|
||||
oneTimeDonationConfiguration.sepaMaximumEuros());
|
||||
}
|
||||
return new OneTimeDonationRequestValidationResult.Success();
|
||||
}
|
||||
|
||||
public static LocalizedPayPalDonationLineItem localizePayPalDonationLineItem(
|
||||
final PayPalDonationsTranslator payPalDonationsTranslator, final List<Locale> acceptableLocales) {
|
||||
// These two localizations are a best-effort, and it's possible that the first `locale` and the localized line
|
||||
// item name will not match. We could try to align with the locales PayPal documents <https://developer.paypal.com/reference/locale-codes/#supported-locale-codes>
|
||||
// but that's a moving target, and we can hopefully have one of them be better for the user by selecting
|
||||
// independently.
|
||||
final Locale locale = SubscriptionsUtil.getPayPalLocale(acceptableLocales);
|
||||
final String localizedLineItemName = payPalDonationsTranslator.translate(acceptableLocales,
|
||||
org.whispersystems.textsecuregcm.subscriptions.PayPalDonationsTranslator.ONE_TIME_DONATION_LINE_ITEM_KEY);
|
||||
return new LocalizedPayPalDonationLineItem(locale, localizedLineItemName);
|
||||
}
|
||||
|
||||
public static DonationLevelDetails getLevelDetails(final PaymentDetails paymentDetails,
|
||||
final OneTimeDonationConfiguration oneTimeDonationConfiguration)
|
||||
throws InvalidLevelException {
|
||||
|
||||
long level = oneTimeDonationConfiguration.boost().level();
|
||||
if (paymentDetails.customMetadata() != null) {
|
||||
final String levelMetadata = paymentDetails.customMetadata()
|
||||
.getOrDefault("level", Long.toString(oneTimeDonationConfiguration.boost().level()));
|
||||
try {
|
||||
level = Long.parseLong(levelMetadata);
|
||||
} catch (final NumberFormatException e) {
|
||||
LOGGER.error("failed to parse level metadata ({}) on payment intent {}", levelMetadata,
|
||||
paymentDetails.id(), e);
|
||||
throw new InvalidLevelException("failed to parse level metadata");
|
||||
}
|
||||
}
|
||||
|
||||
final Duration levelExpiration;
|
||||
if (level == oneTimeDonationConfiguration.boost().level()) {
|
||||
levelExpiration = oneTimeDonationConfiguration.boost().expiration();
|
||||
} else if (level == oneTimeDonationConfiguration.gift().level()) {
|
||||
levelExpiration = oneTimeDonationConfiguration.gift().expiration();
|
||||
} else {
|
||||
LOGGER.error("level ({}) returned from payment intent that is unknown to the server", level);
|
||||
throw new InvalidLevelException("unrecognized level");
|
||||
}
|
||||
return new DonationLevelDetails(level, levelExpiration);
|
||||
}
|
||||
|
||||
}
|
||||
+343
@@ -0,0 +1,343 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil.getClientPlatform;
|
||||
import static org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil.toChargeFailure;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import java.io.IOException;
|
||||
import java.math.BigDecimal;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Optional;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import org.signal.chat.errors.FailedPrecondition;
|
||||
import org.signal.chat.errors.FailedZkAuthentication;
|
||||
import org.signal.chat.errors.NotFound;
|
||||
import org.signal.chat.purchase.AmountAboveSepaLimitError;
|
||||
import org.signal.chat.purchase.AmountBelowMinimumError;
|
||||
import org.signal.chat.purchase.ConfirmPayPalBoostRequest;
|
||||
import org.signal.chat.purchase.ConfirmPayPalBoostResponse;
|
||||
import org.signal.chat.purchase.CreateBoostReceiptCredentialsRequest;
|
||||
import org.signal.chat.purchase.CreateBoostReceiptCredentialsResponse;
|
||||
import org.signal.chat.purchase.CreateBoostRequest;
|
||||
import org.signal.chat.purchase.CreateBoostResponse;
|
||||
import org.signal.chat.purchase.CreatePayPalBoostRequest;
|
||||
import org.signal.chat.purchase.CreatePayPalBoostResponse;
|
||||
import org.signal.chat.purchase.SimpleOneTimeDonationsGrpc;
|
||||
import org.signal.chat.purchase.PaymentRequired;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.VerificationFailedException;
|
||||
import org.signal.libsignal.zkgroup.donation.DonationPermit;
|
||||
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.configuration.OneTimeDonationConfiguration;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.DonationPermitsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.IssuedReceiptsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.OneTimeDonationsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.WriteConflictException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.BraintreeManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PayPalDonationsTranslator;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentDetails;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentStatus;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.StripeManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidAmountException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorException;
|
||||
|
||||
public class OneTimeDonationsGrpcService extends SimpleOneTimeDonationsGrpc.OneTimeDonationsImplBase {
|
||||
|
||||
private final OneTimeDonationConfiguration oneTimeDonationConfiguration;
|
||||
private final StripeManager stripeManager;
|
||||
private final BraintreeManager braintreeManager;
|
||||
private final PayPalDonationsTranslator payPalDonationsTranslator;
|
||||
private final OneTimeDonationsManager oneTimeDonationsManager;
|
||||
private final IssuedReceiptsManager issuedReceiptsManager;
|
||||
private final ServerZkReceiptOperations zkReceiptOperations;
|
||||
private final Clock clock;
|
||||
private final RateLimiters rateLimiters;
|
||||
private final DonationPermitsManager donationPermitsManager;
|
||||
|
||||
public OneTimeDonationsGrpcService(
|
||||
final OneTimeDonationConfiguration oneTimeDonationConfiguration,
|
||||
final StripeManager stripeManager,
|
||||
final BraintreeManager braintreeManager,
|
||||
final PayPalDonationsTranslator payPalDonationsTranslator,
|
||||
final OneTimeDonationsManager oneTimeDonationsManager,
|
||||
final IssuedReceiptsManager issuedReceiptsManager,
|
||||
final ServerZkReceiptOperations zkReceiptOperations,
|
||||
final Clock clock,
|
||||
final RateLimiters rateLimiters,
|
||||
final DonationPermitsManager donationPermitsManager) {
|
||||
this.oneTimeDonationConfiguration = oneTimeDonationConfiguration;
|
||||
this.stripeManager = stripeManager;
|
||||
this.braintreeManager = braintreeManager;
|
||||
this.payPalDonationsTranslator = payPalDonationsTranslator;
|
||||
this.oneTimeDonationsManager = oneTimeDonationsManager;
|
||||
this.issuedReceiptsManager = issuedReceiptsManager;
|
||||
this.zkReceiptOperations = zkReceiptOperations;
|
||||
this.clock = clock;
|
||||
this.rateLimiters = rateLimiters;
|
||||
this.donationPermitsManager = donationPermitsManager;
|
||||
}
|
||||
|
||||
@Override
|
||||
public CreateBoostResponse createBoost(final CreateBoostRequest request)
|
||||
throws RateLimitExceededException {
|
||||
RateLimitUtil.rateLimitByRemoteAddress(rateLimiters.forDescriptor(RateLimiters.For.ONE_TIME_DONATION));
|
||||
|
||||
try {
|
||||
final DonationPermit donationPermit = new DonationPermit(request.getDonationPermit().toByteArray());
|
||||
if (!donationPermitsManager.spend(donationPermit)) {
|
||||
return CreateBoostResponse.newBuilder()
|
||||
.setPermitRejected(FailedZkAuthentication.newBuilder()
|
||||
.setDescription("donation permit rejected")
|
||||
.build())
|
||||
.build();
|
||||
}
|
||||
} catch (InvalidInputException | VerificationFailedException _) {
|
||||
return CreateBoostResponse.newBuilder()
|
||||
.setPermitRejected(FailedZkAuthentication.newBuilder()
|
||||
.setDescription("donation permit rejected")
|
||||
.build())
|
||||
.build();
|
||||
}
|
||||
|
||||
final org.whispersystems.textsecuregcm.subscriptions.PaymentMethod paymentMethod =
|
||||
switch (request.getPaymentMethod()) {
|
||||
case PAYMENT_METHOD_CARD -> org.whispersystems.textsecuregcm.subscriptions.PaymentMethod.CARD;
|
||||
case PAYMENT_METHOD_SEPA_DEBIT -> org.whispersystems.textsecuregcm.subscriptions.PaymentMethod.SEPA_DEBIT;
|
||||
case PAYMENT_METHOD_IDEAL -> org.whispersystems.textsecuregcm.subscriptions.PaymentMethod.IDEAL;
|
||||
default -> throw GrpcExceptions.fieldViolation("payment_method", "Unsupported payment method");
|
||||
};
|
||||
|
||||
final OneTimeDonationUtil.OneTimeDonationRequestValidationResult validationResult =
|
||||
OneTimeDonationUtil.validateOneTimeDonationRequest(
|
||||
request.getCurrency(),
|
||||
BigDecimal.valueOf(request.getAmount()),
|
||||
request.getLevel(),
|
||||
paymentMethod,
|
||||
oneTimeDonationConfiguration,
|
||||
stripeManager);
|
||||
|
||||
return switch (validationResult) {
|
||||
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.UnsupportedLevel _ ->
|
||||
CreateBoostResponse.newBuilder()
|
||||
.setUnsupportedLevel(FailedPrecondition.getDefaultInstance()).build();
|
||||
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.UnsupportedCurrency _ ->
|
||||
CreateBoostResponse.newBuilder()
|
||||
.setUnsupportedCurrency(FailedPrecondition.getDefaultInstance()).build();
|
||||
case final OneTimeDonationUtil.OneTimeDonationRequestValidationResult.AmountBelowMinimum r ->
|
||||
CreateBoostResponse.newBuilder()
|
||||
.setAmountBelowMinimum(AmountBelowMinimumError.newBuilder()
|
||||
.setMinimum(r.minimum().toString()).build()).build();
|
||||
case final OneTimeDonationUtil.OneTimeDonationRequestValidationResult.AmountAboveSepaLimit r ->
|
||||
CreateBoostResponse.newBuilder()
|
||||
.setAmountAboveSepaLimit(AmountAboveSepaLimitError.newBuilder()
|
||||
.setMaximum(r.maximum().toString()).build()).build();
|
||||
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.Success _ -> {
|
||||
try {
|
||||
final com.stripe.model.PaymentIntent paymentIntent = stripeManager.createPaymentIntent(
|
||||
request.getCurrency(), request.getAmount(), request.getLevel(),
|
||||
getClientPlatform(RequestAttributesUtil.getUserAgent().orElse(null)));
|
||||
yield CreateBoostResponse.newBuilder().setClientSecret(paymentIntent.getClientSecret()).build();
|
||||
} catch (final SubscriptionInvalidAmountException e) {
|
||||
yield CreateBoostResponse.newBuilder()
|
||||
.setInvalidAmount(FailedPrecondition.newBuilder()
|
||||
.setDescription(e.getErrorCode()).build())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public CreatePayPalBoostResponse createPayPalBoost(final CreatePayPalBoostRequest request) throws IOException {
|
||||
|
||||
final OneTimeDonationUtil.OneTimeDonationRequestValidationResult validationResult =
|
||||
OneTimeDonationUtil.validateOneTimeDonationRequest(
|
||||
request.getCurrency(),
|
||||
BigDecimal.valueOf(request.getAmount()),
|
||||
request.getLevel(),
|
||||
org.whispersystems.textsecuregcm.subscriptions.PaymentMethod.PAYPAL,
|
||||
oneTimeDonationConfiguration,
|
||||
braintreeManager);
|
||||
|
||||
return switch (validationResult) {
|
||||
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.UnsupportedLevel _ ->
|
||||
CreatePayPalBoostResponse.newBuilder()
|
||||
.setUnsupportedLevel(FailedPrecondition.getDefaultInstance()).build();
|
||||
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.UnsupportedCurrency _ ->
|
||||
CreatePayPalBoostResponse.newBuilder()
|
||||
.setUnsupportedCurrency(FailedPrecondition.getDefaultInstance()).build();
|
||||
case final OneTimeDonationUtil.OneTimeDonationRequestValidationResult.AmountBelowMinimum r ->
|
||||
CreatePayPalBoostResponse.newBuilder()
|
||||
.setAmountBelowMinimum(AmountBelowMinimumError.newBuilder()
|
||||
.setMinimum(r.minimum().toString()).build()).build();
|
||||
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.AmountAboveSepaLimit _ ->
|
||||
throw new IllegalStateException("SEPA limit should not trigger for PayPal");
|
||||
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.Success _ -> {
|
||||
final List<Locale> acceptableLocales = RequestAttributesUtil.getAvailableAcceptedLocales();
|
||||
final OneTimeDonationUtil.LocalizedPayPalDonationLineItem localizedLineItem = OneTimeDonationUtil.localizePayPalDonationLineItem(
|
||||
payPalDonationsTranslator, acceptableLocales);
|
||||
final BraintreeManager.PayPalOneTimePaymentApprovalDetails approvalDetails =
|
||||
braintreeManager.createOneTimePayment(
|
||||
request.getCurrency().toUpperCase(Locale.ROOT), request.getAmount(),
|
||||
localizedLineItem.locale().toLanguageTag(), request.getReturnUrl(), request.getCancelUrl(),
|
||||
localizedLineItem.itemName());
|
||||
yield CreatePayPalBoostResponse.newBuilder()
|
||||
.setResult(CreatePayPalBoostResponse.CreatePayPalBoostResult.newBuilder()
|
||||
.setApprovalUrl(approvalDetails.approvalUrl())
|
||||
.setPaymentId(approvalDetails.paymentId()).build()).build();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public ConfirmPayPalBoostResponse confirmPayPalBoost(final ConfirmPayPalBoostRequest request)
|
||||
throws RateLimitExceededException, IOException {
|
||||
RateLimitUtil.rateLimitByRemoteAddress(rateLimiters.forDescriptor(RateLimiters.For.ONE_TIME_DONATION));
|
||||
|
||||
final OneTimeDonationUtil.OneTimeDonationRequestValidationResult validationResult =
|
||||
OneTimeDonationUtil.validateOneTimeDonationRequest(
|
||||
request.getCurrency(),
|
||||
BigDecimal.valueOf(request.getAmount()),
|
||||
request.getLevel(),
|
||||
org.whispersystems.textsecuregcm.subscriptions.PaymentMethod.PAYPAL,
|
||||
oneTimeDonationConfiguration,
|
||||
braintreeManager);
|
||||
|
||||
return switch (validationResult) {
|
||||
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.UnsupportedLevel _ ->
|
||||
ConfirmPayPalBoostResponse.newBuilder()
|
||||
.setUnsupportedLevel(FailedPrecondition.getDefaultInstance()).build();
|
||||
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.UnsupportedCurrency _ ->
|
||||
ConfirmPayPalBoostResponse.newBuilder()
|
||||
.setUnsupportedCurrency(FailedPrecondition.getDefaultInstance()).build();
|
||||
case final OneTimeDonationUtil.OneTimeDonationRequestValidationResult.AmountBelowMinimum r ->
|
||||
ConfirmPayPalBoostResponse.newBuilder()
|
||||
.setAmountBelowMinimum(AmountBelowMinimumError.newBuilder()
|
||||
.setMinimum(r.minimum().toString()).build()).build();
|
||||
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.AmountAboveSepaLimit _ ->
|
||||
throw new IllegalStateException("SEPA limit should not trigger for PayPal");
|
||||
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.Success _ -> {
|
||||
final BraintreeManager.PayPalChargeSuccessDetails chargeSuccessDetails;
|
||||
try {
|
||||
chargeSuccessDetails = braintreeManager.captureOneTimePayment(
|
||||
request.getPayerId(), request.getPaymentId(), request.getPaymentToken(),
|
||||
request.getCurrency(), request.getAmount(), request.getLevel(),
|
||||
SubscriptionsUtil.getClientPlatform(RequestAttributesUtil.getUserAgent().orElse(null)));
|
||||
oneTimeDonationsManager.putPaidAt(chargeSuccessDetails.paymentId(), clock.instant());
|
||||
yield ConfirmPayPalBoostResponse.newBuilder()
|
||||
.setResult(ConfirmPayPalBoostResponse.ConfirmPayPalBoostResult.newBuilder()
|
||||
.setPaymentId(chargeSuccessDetails.paymentId()).build()).build();
|
||||
} catch (final SubscriptionProcessorException e) {
|
||||
yield ConfirmPayPalBoostResponse.newBuilder()
|
||||
.setChargeFailure(SubscriptionsUtil.toChargeFailure(e.getProcessor(), e.getChargeFailure()))
|
||||
.build();
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public CreateBoostReceiptCredentialsResponse createBoostReceiptCredentials(
|
||||
final CreateBoostReceiptCredentialsRequest request) throws IOException {
|
||||
|
||||
final PaymentProvider processor;
|
||||
final Optional<PaymentDetails> maybePaymentDetails;
|
||||
switch (request.getProcessor()) {
|
||||
case PAYMENT_PROVIDER_STRIPE -> {
|
||||
processor = PaymentProvider.STRIPE;
|
||||
maybePaymentDetails = stripeManager.getPaymentDetails(request.getPaymentIntentId());
|
||||
}
|
||||
case PAYMENT_PROVIDER_BRAINTREE -> {
|
||||
processor = PaymentProvider.BRAINTREE;
|
||||
maybePaymentDetails = braintreeManager.getPaymentDetails(request.getPaymentIntentId());
|
||||
}
|
||||
default -> throw GrpcExceptions.fieldViolation("processor", "Unsupported payment processor");
|
||||
}
|
||||
|
||||
if (maybePaymentDetails.isEmpty()) {
|
||||
return CreateBoostReceiptCredentialsResponse.newBuilder()
|
||||
.setPaymentNotFound(NotFound.getDefaultInstance()).build();
|
||||
}
|
||||
final PaymentDetails paymentDetails = maybePaymentDetails.get();
|
||||
if (paymentDetails.status() == PaymentStatus.PROCESSING) {
|
||||
return CreateBoostReceiptCredentialsResponse.newBuilder()
|
||||
.setPaymentStillProcessing(FailedPrecondition.getDefaultInstance()).build();
|
||||
}
|
||||
if (paymentDetails.status() != PaymentStatus.SUCCEEDED) {
|
||||
final PaymentRequired.Builder paymentRequiredBuilder = PaymentRequired.newBuilder();
|
||||
if (paymentDetails.chargeFailure() != null) {
|
||||
paymentRequiredBuilder.setChargeFailure(toChargeFailure(processor, paymentDetails.chargeFailure()));
|
||||
}
|
||||
return CreateBoostReceiptCredentialsResponse.newBuilder()
|
||||
.setPaymentRequired(paymentRequiredBuilder).build();
|
||||
}
|
||||
|
||||
final OneTimeDonationUtil.DonationLevelDetails levelDetails;
|
||||
try {
|
||||
levelDetails = OneTimeDonationUtil.getLevelDetails(paymentDetails, oneTimeDonationConfiguration);
|
||||
} catch (final OneTimeDonationUtil.InvalidLevelException e) {
|
||||
throw GrpcExceptions.unavailable(e.getMessage());
|
||||
}
|
||||
|
||||
final ReceiptCredentialRequest receiptCredentialRequest;
|
||||
try {
|
||||
receiptCredentialRequest = new ReceiptCredentialRequest(
|
||||
request.getReceiptCredentialRequest().toByteArray());
|
||||
} catch (final InvalidInputException e) {
|
||||
throw GrpcExceptions.fieldViolation("receipt_credential_request", "invalid receipt credential request");
|
||||
}
|
||||
|
||||
try {
|
||||
issuedReceiptsManager.recordIssuance(
|
||||
paymentDetails.id(), processor, receiptCredentialRequest, clock.instant());
|
||||
} catch (final WriteConflictException e) {
|
||||
return CreateBoostReceiptCredentialsResponse.newBuilder()
|
||||
.setReceiptAlreadyIssued(FailedPrecondition.getDefaultInstance()).build();
|
||||
}
|
||||
|
||||
final Instant paidAt = oneTimeDonationsManager.getPaidAt(paymentDetails.id(), paymentDetails.created());
|
||||
final Instant expiration = paidAt
|
||||
.plus(levelDetails.levelExpiration())
|
||||
.truncatedTo(ChronoUnit.DAYS)
|
||||
.plus(1, ChronoUnit.DAYS);
|
||||
|
||||
final ReceiptCredentialResponse receiptCredentialResponse;
|
||||
try {
|
||||
receiptCredentialResponse = zkReceiptOperations.issueReceiptCredential(
|
||||
receiptCredentialRequest, expiration.getEpochSecond(), levelDetails.level());
|
||||
} catch (final VerificationFailedException e) {
|
||||
throw GrpcExceptions.fieldViolation("receipt_credential_request",
|
||||
"receipt credential request failed verification");
|
||||
}
|
||||
|
||||
Metrics.counter(SubscriptionsGrpcService.RECEIPT_ISSUED_COUNTER_NAME,
|
||||
Tags.of(
|
||||
Tag.of(SubscriptionsGrpcService.PROCESSOR_TAG_NAME, processor.toString()),
|
||||
Tag.of(SubscriptionsGrpcService.TYPE_TAG_NAME, "boost"),
|
||||
UserAgentTagUtil.getPlatformTag(RequestAttributesUtil.getUserAgent().orElse(null))))
|
||||
.increment();
|
||||
|
||||
return CreateBoostReceiptCredentialsResponse.newBuilder()
|
||||
.setResult(CreateBoostReceiptCredentialsResponse.CreateBoostReceiptCredentialsResult.newBuilder()
|
||||
.setReceiptCredentialResponse(ByteString.copyFrom(receiptCredentialResponse.serialize()))
|
||||
.build())
|
||||
.build();
|
||||
}
|
||||
|
||||
}
|
||||
+167
@@ -0,0 +1,167 @@
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import com.google.protobuf.CodedOutputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.math.BigDecimal;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.stream.Collectors;
|
||||
import org.signal.chat.purchase.AmountList;
|
||||
import org.signal.chat.purchase.BackupConfiguration;
|
||||
import org.signal.chat.purchase.BackupLevelConfiguration;
|
||||
import org.signal.chat.purchase.Configuration;
|
||||
import org.signal.chat.purchase.CurrencyConfiguration;
|
||||
import org.signal.chat.purchase.GetConfigurationRequest;
|
||||
import org.signal.chat.purchase.GetConfigurationResponse;
|
||||
import org.signal.chat.purchase.LevelConfiguration;
|
||||
import org.signal.chat.purchase.SimpleProductConfigurationGrpc;
|
||||
import org.signal.chat.purchase.TaggedConfiguration;
|
||||
import org.whispersystems.textsecuregcm.badges.BadgeTranslator;
|
||||
import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.SubscriptionConfiguration;
|
||||
import org.whispersystems.textsecuregcm.entities.PurchasableBadge;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.CustomerAwareSubscriptionPaymentProcessor;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentMethod;
|
||||
|
||||
public class ProductConfigurationGrpcService extends SimpleProductConfigurationGrpc.ProductConfigurationImplBase {
|
||||
|
||||
private final SubscriptionConfiguration subscriptionConfiguration;
|
||||
private final OneTimeDonationConfiguration oneTimeDonationConfiguration;
|
||||
private final BadgeTranslator badgeTranslator;
|
||||
|
||||
// These portions of the configuration are identical on every request
|
||||
private final Map<String, CurrencyConfiguration> currencyConfigurations;
|
||||
private final BackupConfiguration backupConfiguration;
|
||||
|
||||
// The configuration varies based on the provided Accept-Language header. Here we cache the eTag for the resolved
|
||||
// language, so if the caller provides a matching etag we don't have to build the full configuration match.
|
||||
private final ConcurrentHashMap<Locale, ByteString> localeToEtag = new ConcurrentHashMap<>();
|
||||
|
||||
|
||||
public ProductConfigurationGrpcService(
|
||||
final SubscriptionConfiguration subscriptionConfiguration,
|
||||
final OneTimeDonationConfiguration oneTimeDonationConfiguration,
|
||||
List<CustomerAwareSubscriptionPaymentProcessor> paymentProcessors,
|
||||
final BadgeTranslator badgeTranslator,
|
||||
final long backupMediaStorageAllowanceBytes) {
|
||||
this.subscriptionConfiguration = subscriptionConfiguration;
|
||||
this.oneTimeDonationConfiguration = oneTimeDonationConfiguration;
|
||||
this.badgeTranslator = badgeTranslator;
|
||||
this.backupConfiguration = buildBackupConfiguration(subscriptionConfiguration, backupMediaStorageAllowanceBytes);
|
||||
this.currencyConfigurations =
|
||||
buildCurrencyConfigurations(subscriptionConfiguration, oneTimeDonationConfiguration, paymentProcessors);
|
||||
}
|
||||
|
||||
@Override
|
||||
public GetConfigurationResponse getConfiguration(final GetConfigurationRequest request) {
|
||||
final Locale locale = badgeTranslator.resolveLocale(RequestAttributesUtil.getAvailableAcceptedLocales());
|
||||
final ByteString etag = localeToEtag.get(locale);
|
||||
if (etag != null && etag.equals(request.getEtag())) {
|
||||
return GetConfigurationResponse.newBuilder().setEtagMatched(true).build();
|
||||
}
|
||||
|
||||
final Map<Long, LevelConfiguration> levelConfigurations = SubscriptionsUtil
|
||||
.buildDonationLevelsConfiguration(subscriptionConfiguration, oneTimeDonationConfiguration, badgeTranslator,
|
||||
RequestAttributesUtil.getAvailableAcceptedLocales())
|
||||
.entrySet().stream().collect(Collectors.toMap(
|
||||
Map.Entry::getKey,
|
||||
entry -> toProtoLevelConfiguration(entry.getValue())));
|
||||
|
||||
final Configuration configuration = Configuration.newBuilder()
|
||||
.putAllCurrencies(currencyConfigurations)
|
||||
.putAllBadgeLevels(levelConfigurations)
|
||||
.setBackup(backupConfiguration)
|
||||
.setSepaMaximumEuros(oneTimeDonationConfiguration.sepaMaximumEuros().toString()).build();
|
||||
final TaggedConfiguration taggedConfiguration = calculateEtag(configuration);
|
||||
|
||||
// This could race and multiple threads could decide to build-and-cache. That's fine, they should all calculate
|
||||
// the same etag.
|
||||
localeToEtag.put(locale, taggedConfiguration.getEtag());
|
||||
return GetConfigurationResponse.newBuilder().setTaggedConfiguration(taggedConfiguration).build();
|
||||
}
|
||||
|
||||
private static TaggedConfiguration calculateEtag(final Configuration configuration) {
|
||||
final ByteArrayOutputStream baos = new ByteArrayOutputStream(configuration.getSerializedSize());
|
||||
final CodedOutputStream cos = CodedOutputStream.newInstance(baos);
|
||||
cos.useDeterministicSerialization();
|
||||
try {
|
||||
configuration.writeTo(cos);
|
||||
cos.flush();
|
||||
final byte[] configurationBytes = baos.toByteArray();
|
||||
byte[] hash = MessageDigest.getInstance("SHA-256").digest(configurationBytes);
|
||||
return TaggedConfiguration.newBuilder()
|
||||
.setConfiguration(configuration)
|
||||
.setEtag(ByteString.copyFrom(hash))
|
||||
.build();
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
}
|
||||
|
||||
private static Map<String, CurrencyConfiguration> buildCurrencyConfigurations(
|
||||
final SubscriptionConfiguration subscriptionConfiguration,
|
||||
final OneTimeDonationConfiguration oneTimeDonationConfiguration,
|
||||
List<CustomerAwareSubscriptionPaymentProcessor> paymentProcessors) {
|
||||
return SubscriptionsUtil
|
||||
.buildCurrencyConfiguration(paymentProcessors, oneTimeDonationConfiguration, subscriptionConfiguration)
|
||||
.entrySet().stream()
|
||||
.collect(Collectors.toMap(
|
||||
Map.Entry::getKey,
|
||||
e -> toProtoCurrencyConfiguration(e.getKey(), e.getValue())));
|
||||
}
|
||||
|
||||
private static BackupConfiguration buildBackupConfiguration(final SubscriptionConfiguration subscriptionConfiguration,
|
||||
final long backupMediaStorageAllowanceBytes) {
|
||||
final Map<Long, BackupLevelConfiguration> backupLevels =
|
||||
subscriptionConfiguration.getBackupLevels().entrySet().stream().collect(Collectors.toMap(
|
||||
Map.Entry::getKey,
|
||||
e -> BackupLevelConfiguration.newBuilder()
|
||||
.setStorageAllowanceBytes(backupMediaStorageAllowanceBytes)
|
||||
.setPlayProductId(e.getValue().playProductId())
|
||||
.setMediaTtlDays(e.getValue().mediaTtl().toDays())
|
||||
.build()));
|
||||
return BackupConfiguration.newBuilder()
|
||||
.putAllLevels(backupLevels)
|
||||
.setFreeTierMediaDays(subscriptionConfiguration.getbackupFreeTierMediaDuration().toDays())
|
||||
.build();
|
||||
}
|
||||
|
||||
private static CurrencyConfiguration toProtoCurrencyConfiguration(
|
||||
final String currency,
|
||||
final org.whispersystems.textsecuregcm.subscriptions.CurrencyConfiguration config) {
|
||||
final CurrencyConfiguration.Builder builder = CurrencyConfiguration.newBuilder()
|
||||
.setMinimum(config.minimum().toString())
|
||||
.addAllSupportedPaymentMethods(config.supportedPaymentMethods().stream()
|
||||
.map(PaymentMethod::toProtoPaymentMethod)
|
||||
.toList());
|
||||
config.oneTime().forEach((levelId, amounts) ->
|
||||
builder.putOneTime(levelId, AmountList.newBuilder()
|
||||
.addAllAmounts(amounts.stream().map(BigDecimal::toString).toList())
|
||||
.build()));
|
||||
config.subscription()
|
||||
.forEach((levelId, amount) -> builder.putSubscription(levelId, amount.toString()));
|
||||
config.backupSubscription()
|
||||
.forEach((levelId, amount) -> builder.putBackupSubscription(levelId, amount.toString()));
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
private static LevelConfiguration toProtoLevelConfiguration(
|
||||
final org.whispersystems.textsecuregcm.subscriptions.LevelConfiguration levelConfiguration) {
|
||||
final LevelConfiguration.Builder builder = LevelConfiguration.newBuilder();
|
||||
if (levelConfiguration.badge() instanceof final PurchasableBadge purchasableBadge) {
|
||||
builder.setBadgeDurationSeconds(purchasableBadge.getDuration().toSeconds());
|
||||
}
|
||||
return builder
|
||||
.setBadge(BadgeGrpcHelper.toGrpcBadge(levelConfiguration.badge()))
|
||||
.build();
|
||||
}
|
||||
}
|
||||
+147
-6
@@ -5,12 +5,21 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.util.Optional;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.protobuf.Empty;
|
||||
import java.time.Clock;
|
||||
import java.util.Base64;
|
||||
import java.util.Optional;
|
||||
import org.signal.chat.errors.FailedUnidentifiedAuthorization;
|
||||
import org.signal.chat.errors.FailedZkAuthentication;
|
||||
import org.signal.chat.errors.NotFound;
|
||||
import org.signal.chat.profile.CredentialType;
|
||||
import org.signal.chat.profile.DeleteAvatarRequest;
|
||||
import org.signal.chat.profile.DeleteAvatarResponse;
|
||||
import org.signal.chat.profile.ExtendAvatarTTLRequest;
|
||||
import org.signal.chat.profile.ExtendAvatarTTLResponse;
|
||||
import org.signal.chat.profile.GetAvatarUploadFormRequest;
|
||||
import org.signal.chat.profile.GetAvatarUploadFormResponse;
|
||||
import org.signal.chat.profile.GetExpiringProfileKeyCredentialAnonymousRequest;
|
||||
import org.signal.chat.profile.GetExpiringProfileKeyCredentialAnonymousResponse;
|
||||
import org.signal.chat.profile.GetUnversionedProfileAnonymousRequest;
|
||||
@@ -18,44 +27,75 @@ import org.signal.chat.profile.GetUnversionedProfileAnonymousResponse;
|
||||
import org.signal.chat.profile.GetVersionedProfileAnonymousRequest;
|
||||
import org.signal.chat.profile.GetVersionedProfileAnonymousResponse;
|
||||
import org.signal.chat.profile.SimpleProfileAnonymousGrpc;
|
||||
import org.signal.libsignal.zkgroup.GenericServerSecretParams;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.ServerSecretParams;
|
||||
import org.signal.libsignal.zkgroup.VerificationFailedException;
|
||||
import org.signal.libsignal.zkgroup.avatars.AvatarUploadCredentialPresentation;
|
||||
import org.signal.libsignal.zkgroup.profiles.ServerZkProfileOperations;
|
||||
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
|
||||
import org.whispersystems.textsecuregcm.badges.ProfileBadgeConverter;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
|
||||
import org.whispersystems.textsecuregcm.util.ProfileHelper;
|
||||
|
||||
public class ProfileAnonymousGrpcService extends SimpleProfileAnonymousGrpc.ProfileAnonymousImplBase {
|
||||
private final AccountsManager accountsManager;
|
||||
private final ProfilesManager profilesManager;
|
||||
private final ProfileBadgeConverter profileBadgeConverter;
|
||||
private final ServerZkProfileOperations zkProfileOperations;
|
||||
private final GenericServerSecretParams genericServerSecretParams;
|
||||
private final GroupSendTokenUtil groupSendTokenUtil;
|
||||
|
||||
private final PostPolicyGenerator policyGenerator;
|
||||
|
||||
private final RateLimiters rateLimiters;
|
||||
|
||||
private final Clock clock;
|
||||
|
||||
public ProfileAnonymousGrpcService(
|
||||
final AccountsManager accountsManager,
|
||||
final ProfilesManager profilesManager,
|
||||
final ProfileBadgeConverter profileBadgeConverter,
|
||||
final ServerSecretParams serverSecretParams) {
|
||||
final PostPolicyGenerator policyGenerator,
|
||||
final GenericServerSecretParams genericServerSecretParams,
|
||||
final ServerSecretParams serverSecretParams,
|
||||
final RateLimiters rateLimiters,
|
||||
final Clock clock) {
|
||||
this(accountsManager,
|
||||
profilesManager,
|
||||
profileBadgeConverter,
|
||||
policyGenerator,
|
||||
genericServerSecretParams,
|
||||
rateLimiters,
|
||||
clock,
|
||||
new ServerZkProfileOperations(serverSecretParams),
|
||||
new GroupSendTokenUtil(serverSecretParams, Clock.systemUTC()));
|
||||
new GroupSendTokenUtil(serverSecretParams, clock));
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
ProfileAnonymousGrpcService(final AccountsManager accountsManager,
|
||||
final ProfilesManager profilesManager,
|
||||
final ProfileBadgeConverter profileBadgeConverter,
|
||||
final PostPolicyGenerator policyGenerator,
|
||||
final GenericServerSecretParams genericServerSecretParams,
|
||||
final RateLimiters rateLimiters,
|
||||
final Clock clock,
|
||||
final ServerZkProfileOperations zkProfileOperations,
|
||||
final GroupSendTokenUtil groupSendTokenUtil) {
|
||||
this.accountsManager = accountsManager;
|
||||
this.profilesManager = profilesManager;
|
||||
this.profileBadgeConverter = profileBadgeConverter;
|
||||
this.policyGenerator = policyGenerator;
|
||||
this.genericServerSecretParams = genericServerSecretParams;
|
||||
this.rateLimiters = rateLimiters;
|
||||
this.clock = clock;
|
||||
this.zkProfileOperations = zkProfileOperations;
|
||||
this.groupSendTokenUtil = groupSendTokenUtil;
|
||||
}
|
||||
@@ -89,7 +129,6 @@ public class ProfileAnonymousGrpcService extends SimpleProfileAnonymousGrpc.Prof
|
||||
return targetAccount.map(account ->
|
||||
GetUnversionedProfileAnonymousResponse.newBuilder()
|
||||
.setResult(ProfileGrpcHelper.buildUnversionedProfileResult(targetIdentifier,
|
||||
null,
|
||||
account,
|
||||
profileBadgeConverter))
|
||||
.build())
|
||||
@@ -102,7 +141,21 @@ public class ProfileAnonymousGrpcService extends SimpleProfileAnonymousGrpc.Prof
|
||||
public GetVersionedProfileAnonymousResponse getVersionedProfile(final GetVersionedProfileAnonymousRequest request) {
|
||||
final ServiceIdentifier targetIdentifier = GrpcServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getRequest().getAccountIdentifier());
|
||||
|
||||
final Optional<Account> targetAccount = getTargetAccountAndValidateUnidentifiedAccess(targetIdentifier, request.getUnidentifiedAccessKey().toByteArray());
|
||||
final Optional<Account> targetAccount = accountsManager.getByServiceIdentifier(targetIdentifier);
|
||||
|
||||
final boolean authorized = switch (request.getAuthenticationCase()) {
|
||||
case GROUP_SEND_TOKEN -> groupSendTokenUtil.checkGroupSendToken(request.getGroupSendToken(), targetIdentifier);
|
||||
case UNIDENTIFIED_ACCESS_KEY ->
|
||||
targetAccount.map(a -> UnidentifiedAccessUtil.checkUnidentifiedAccess(a, request.getUnidentifiedAccessKey().toByteArray()))
|
||||
.orElse(false);
|
||||
default -> throw GrpcExceptions.invalidArguments("invalid authentication");
|
||||
};
|
||||
|
||||
if (!authorized) {
|
||||
return GetVersionedProfileAnonymousResponse.newBuilder()
|
||||
.setFailedUnidentifiedAuthorization(FailedUnidentifiedAuthorization.getDefaultInstance())
|
||||
.build();
|
||||
}
|
||||
|
||||
return targetAccount.flatMap(account ->
|
||||
ProfileGrpcHelper.getVersionedProfile(account,
|
||||
@@ -152,4 +205,92 @@ public class ProfileAnonymousGrpcService extends SimpleProfileAnonymousGrpc.Prof
|
||||
return accountsManager.getByServiceIdentifier(targetIdentifier)
|
||||
.filter(targetAccount -> UnidentifiedAccessUtil.checkUnidentifiedAccess(targetAccount, unidentifiedAccessKey));
|
||||
}
|
||||
|
||||
@Override
|
||||
public GetAvatarUploadFormResponse getAvatarUploadForm(final GetAvatarUploadFormRequest request) throws RateLimitExceededException {
|
||||
final AvatarUploadCredentialPresentation presentation;
|
||||
|
||||
try {
|
||||
presentation = new AvatarUploadCredentialPresentation(
|
||||
request.getAvatarCredentialsPresentation().toByteArray());
|
||||
|
||||
presentation.verify(clock.instant(), this.genericServerSecretParams);
|
||||
|
||||
} catch (InvalidInputException _) {
|
||||
throw GrpcExceptions.invalidArguments("invalid credential presentation");
|
||||
|
||||
} catch (VerificationFailedException _) {
|
||||
return GetAvatarUploadFormResponse.newBuilder()
|
||||
.setInvalidCredentialsPresentation(FailedZkAuthentication.getDefaultInstance())
|
||||
.build();
|
||||
}
|
||||
|
||||
final byte[] identity = presentation.getCommitment();
|
||||
|
||||
rateLimiters.getProfileAvatarBytesLimiter().validate(Base64.getEncoder().encodeToString(identity), request.getUploadLength());
|
||||
|
||||
final String avatar = ProfileHelper.generateAvatarObjectName();
|
||||
|
||||
profilesManager.setAvatarForIdentity(identity, avatar);
|
||||
|
||||
return GetAvatarUploadFormResponse.newBuilder()
|
||||
.setAvatarUploadForm(ProfileGrpcHelper.generateAvatarUploadForm(avatar, request.getUploadLength(), policyGenerator, clock))
|
||||
.build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ExtendAvatarTTLResponse extendAvatarTTL(final ExtendAvatarTTLRequest request) {
|
||||
final AvatarUploadCredentialPresentation presentation;
|
||||
try {
|
||||
presentation = new AvatarUploadCredentialPresentation(
|
||||
request.getAvatarCredentialsPresentation().toByteArray());
|
||||
} catch (InvalidInputException _) {
|
||||
throw GrpcExceptions.invalidArguments("invalid credential presentation");
|
||||
}
|
||||
|
||||
try {
|
||||
presentation.verify(clock.instant(), this.genericServerSecretParams);
|
||||
|
||||
} catch (VerificationFailedException _) {
|
||||
return ExtendAvatarTTLResponse.newBuilder()
|
||||
.setInvalidCredentialsPresentation(FailedZkAuthentication.getDefaultInstance())
|
||||
.build();
|
||||
}
|
||||
|
||||
final byte[] identity = presentation.getCommitment();
|
||||
|
||||
return profilesManager.extendAvatarTtlForIdentity(identity)
|
||||
.map(extendedPath -> ExtendAvatarTTLResponse.newBuilder()
|
||||
.setPath(extendedPath)
|
||||
.build())
|
||||
.orElseGet(() -> ExtendAvatarTTLResponse.newBuilder()
|
||||
.setNotFound(NotFound.getDefaultInstance())
|
||||
.build());
|
||||
}
|
||||
|
||||
@Override
|
||||
public DeleteAvatarResponse deleteAvatar(final DeleteAvatarRequest request) {
|
||||
final AvatarUploadCredentialPresentation presentation;
|
||||
try {
|
||||
presentation = new AvatarUploadCredentialPresentation(
|
||||
request.getAvatarCredentialsPresentation().toByteArray());
|
||||
} catch (InvalidInputException _) {
|
||||
throw GrpcExceptions.invalidArguments("invalid credential presentation");
|
||||
}
|
||||
|
||||
try {
|
||||
presentation.verify(clock.instant(), this.genericServerSecretParams);
|
||||
|
||||
} catch (VerificationFailedException _) {
|
||||
return DeleteAvatarResponse.newBuilder()
|
||||
.setInvalidCredentialsPresentation(FailedZkAuthentication.getDefaultInstance())
|
||||
.build();
|
||||
}
|
||||
|
||||
final byte[] identity = presentation.getCommitment();
|
||||
|
||||
profilesManager.deleteAvatarForIdentity(identity);
|
||||
|
||||
return DeleteAvatarResponse.newBuilder().setSuccess(Empty.getDefaultInstance()).build();
|
||||
}
|
||||
}
|
||||
+32
-38
@@ -9,14 +9,13 @@ import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.protobuf.ByteString;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.ArrayList;
|
||||
import java.time.Clock;
|
||||
import java.util.Arrays;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import org.signal.chat.profile.Badge;
|
||||
import org.signal.chat.profile.BadgeSvg;
|
||||
import org.signal.chat.common.S3UploadForm;
|
||||
import org.signal.chat.profile.DataEtag;
|
||||
import org.signal.chat.profile.GetExpiringProfileKeyCredentialResult;
|
||||
import org.signal.chat.profile.GetUnversionedProfileResult;
|
||||
@@ -31,7 +30,9 @@ import org.signal.libsignal.zkgroup.profiles.ProfileKeyCredentialRequest;
|
||||
import org.signal.libsignal.zkgroup.profiles.ServerZkProfileOperations;
|
||||
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessChecksum;
|
||||
import org.whispersystems.textsecuregcm.badges.ProfileBadgeConverter;
|
||||
import org.whispersystems.textsecuregcm.entities.Badge;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
|
||||
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
|
||||
@@ -40,6 +41,12 @@ import org.whispersystems.textsecuregcm.storage.VersionedProfileV1;
|
||||
import org.whispersystems.textsecuregcm.util.ProfileHelper;
|
||||
|
||||
public class ProfileGrpcHelper {
|
||||
|
||||
private static final S3UploadForm PROTOTYPE_AVATAR_UPLOAD_FORM = S3UploadForm.newBuilder()
|
||||
.setAcl(PostPolicyGenerator.ACL)
|
||||
.setAlgorithm(PostPolicyGenerator.ALGORITHM)
|
||||
.build();
|
||||
|
||||
static Optional<GetVersionedProfileResult> getVersionedProfile(final Account account,
|
||||
final ProfilesManager profilesManager,
|
||||
final byte[] requestVersion,
|
||||
@@ -120,23 +127,6 @@ public class ProfileGrpcHelper {
|
||||
return Optional.of(responseBuilder.build());
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static List<Badge> buildBadges(final List<org.whispersystems.textsecuregcm.entities.Badge> badges) {
|
||||
final ArrayList<Badge> grpcBadges = new ArrayList<>();
|
||||
for (final org.whispersystems.textsecuregcm.entities.Badge badge : badges) {
|
||||
grpcBadges.add(Badge.newBuilder()
|
||||
.setId(badge.getId())
|
||||
.setCategory(badge.getCategory())
|
||||
.setName(badge.getName())
|
||||
.setDescription(badge.getDescription())
|
||||
.addAllSprites6(badge.getSprites6())
|
||||
.setSvg(badge.getSvg())
|
||||
.addAllSvgs(buildBadgeSvgs(badge.getSvgs()))
|
||||
.build());
|
||||
}
|
||||
return grpcBadges;
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static List<org.signal.chat.common.DeviceCapability> buildAccountCapabilities(final Account account) {
|
||||
return Arrays.stream(DeviceCapability.values())
|
||||
@@ -146,20 +136,8 @@ public class ProfileGrpcHelper {
|
||||
.toList();
|
||||
}
|
||||
|
||||
private static List<BadgeSvg> buildBadgeSvgs(final List<org.whispersystems.textsecuregcm.entities.BadgeSvg> badgeSvgs) {
|
||||
ArrayList<BadgeSvg> grpcBadgeSvgs = new ArrayList<>();
|
||||
for (final org.whispersystems.textsecuregcm.entities.BadgeSvg badgeSvg : badgeSvgs) {
|
||||
grpcBadgeSvgs.add(BadgeSvg.newBuilder()
|
||||
.setDark(badgeSvg.getDark())
|
||||
.setLight(badgeSvg.getLight())
|
||||
.build());
|
||||
}
|
||||
return grpcBadgeSvgs;
|
||||
}
|
||||
|
||||
static GetUnversionedProfileResult buildUnversionedProfileResult(
|
||||
final ServiceIdentifier targetIdentifier,
|
||||
final UUID requesterUuid,
|
||||
final Account targetAccount,
|
||||
final ProfileBadgeConverter profileBadgeConverter) {
|
||||
final GetUnversionedProfileResult.Builder resultBuilder = GetUnversionedProfileResult.newBuilder()
|
||||
@@ -168,11 +146,13 @@ public class ProfileGrpcHelper {
|
||||
|
||||
switch (targetIdentifier.identityType()) {
|
||||
case ACI -> {
|
||||
resultBuilder.setUnrestrictedUnidentifiedAccess(targetAccount.isUnrestrictedUnidentifiedAccess())
|
||||
.addAllBadges(
|
||||
buildBadges(profileBadgeConverter.convert(RequestAttributesUtil.getAvailableAcceptedLocales(),
|
||||
targetAccount.getBadges(),
|
||||
ProfileHelper.isSelfProfileRequest(requesterUuid, targetIdentifier))));
|
||||
final List<Locale> acceptedLocales = RequestAttributesUtil.getAvailableAcceptedLocales();
|
||||
final List<Badge> badges =
|
||||
profileBadgeConverter.convert(acceptedLocales, targetAccount.getBadges(), false);
|
||||
|
||||
resultBuilder
|
||||
.setUnrestrictedUnidentifiedAccess(targetAccount.isUnrestrictedUnidentifiedAccess())
|
||||
.addAllBadges(badges.stream().map(BadgeGrpcHelper::toGrpcBadge).toList());
|
||||
|
||||
targetAccount.getUnidentifiedAccessKey()
|
||||
.map(UnidentifiedAccessChecksum::generateFor)
|
||||
@@ -217,6 +197,20 @@ public class ProfileGrpcHelper {
|
||||
});
|
||||
}
|
||||
|
||||
public static S3UploadForm generateAvatarUploadForm(final String objectName, final int uploadLength,
|
||||
final PostPolicyGenerator policyGenerator, final Clock clock) {
|
||||
final PostPolicyGenerator.SignedPostPolicy policy =
|
||||
policyGenerator.createFor(objectName, uploadLength, clock.instant());
|
||||
|
||||
return PROTOTYPE_AVATAR_UPLOAD_FORM.toBuilder()
|
||||
.setKey(objectName)
|
||||
.setCredential(policy.credential())
|
||||
.setDate(policy.formattedTimestamp())
|
||||
.setPolicy(policy.encodedPolicy())
|
||||
.setSignature(policy.signature())
|
||||
.build();
|
||||
}
|
||||
|
||||
/**
|
||||
* Computes the SHA-256 hash of the given data.
|
||||
* <p>
|
||||
|
||||
+53
-26
@@ -7,29 +7,40 @@ package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import java.time.Clock;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.Arrays;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
import org.signal.chat.common.S3UploadForm;
|
||||
import org.signal.chat.errors.FailedPrecondition;
|
||||
import org.signal.chat.errors.NotFound;
|
||||
import org.signal.chat.profile.GetAvatarCredentialsRequest;
|
||||
import org.signal.chat.profile.GetAvatarCredentialsResponse;
|
||||
import org.signal.chat.profile.GetUnversionedProfileRequest;
|
||||
import org.signal.chat.profile.GetUnversionedProfileResponse;
|
||||
import org.signal.chat.profile.GetVersionedProfileRequest;
|
||||
import org.signal.chat.profile.GetVersionedProfileResponse;
|
||||
import org.signal.chat.profile.PaymentsForbiddenInRegion;
|
||||
import org.signal.chat.profile.ProfileAvatarUploadAttributes;
|
||||
import org.signal.chat.profile.ProfilesV2CapabilityRequired;
|
||||
import org.signal.chat.profile.SetProfileRequest;
|
||||
import org.signal.chat.profile.SetProfileResponse;
|
||||
import org.signal.chat.profile.SetProfileResult;
|
||||
import org.signal.chat.profile.SetProfileV1Request.AvatarChange;
|
||||
import org.signal.chat.profile.SimpleProfileGrpc;
|
||||
import org.signal.libsignal.protocol.ServiceId;
|
||||
import org.signal.libsignal.zkgroup.GenericServerSecretParams;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.VerificationFailedException;
|
||||
import org.signal.libsignal.zkgroup.avatars.AvatarUploadCredentialRequest;
|
||||
import org.signal.libsignal.zkgroup.avatars.AvatarUploadCredentialResponse;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
|
||||
import org.whispersystems.textsecuregcm.badges.ProfileBadgeConverter;
|
||||
@@ -40,7 +51,6 @@ import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.s3.PolicySigner;
|
||||
import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountBadge;
|
||||
@@ -51,24 +61,25 @@ import org.whispersystems.textsecuregcm.storage.ProfilesManager;
|
||||
import org.whispersystems.textsecuregcm.storage.VersionedProfile;
|
||||
import org.whispersystems.textsecuregcm.storage.VersionedProfileV1;
|
||||
import org.whispersystems.textsecuregcm.storage.WriteConflictException;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import org.whispersystems.textsecuregcm.util.ProfileHelper;
|
||||
|
||||
public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(ProfileGrpcService.class);
|
||||
|
||||
private final Clock clock;
|
||||
private final AccountsManager accountsManager;
|
||||
private final ProfilesManager profilesManager;
|
||||
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
|
||||
private final Map<String, BadgeConfiguration> badgeConfigurationMap;
|
||||
private final PostPolicyGenerator policyGenerator;
|
||||
private final PolicySigner policySigner;
|
||||
private final GenericServerSecretParams genericServerSecretParams;
|
||||
private final ProfileBadgeConverter profileBadgeConverter;
|
||||
private final RateLimiters rateLimiters;
|
||||
|
||||
private record AvatarData(Optional<String> currentAvatar,
|
||||
Optional<String> finalAvatar,
|
||||
Optional<ProfileAvatarUploadAttributes> uploadAttributes) {}
|
||||
Optional<S3UploadForm> uploadAttributes) {}
|
||||
|
||||
public ProfileGrpcService(
|
||||
final Clock clock,
|
||||
@@ -77,7 +88,7 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
|
||||
final BadgesConfiguration badgesConfiguration,
|
||||
final PostPolicyGenerator policyGenerator,
|
||||
final PolicySigner policySigner,
|
||||
final GenericServerSecretParams genericServerSecretParams,
|
||||
final ProfileBadgeConverter profileBadgeConverter,
|
||||
final RateLimiters rateLimiters) {
|
||||
this.clock = clock;
|
||||
@@ -87,7 +98,7 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
|
||||
this.badgeConfigurationMap = badgesConfiguration.getBadges().stream().collect(Collectors.toMap(
|
||||
BadgeConfiguration::getId, Function.identity()));
|
||||
this.policyGenerator = policyGenerator;
|
||||
this.policySigner = policySigner;
|
||||
this.genericServerSecretParams = genericServerSecretParams;
|
||||
this.profileBadgeConverter = profileBadgeConverter;
|
||||
this.rateLimiters = rateLimiters;
|
||||
}
|
||||
@@ -138,7 +149,7 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
|
||||
case AVATAR_CHANGE_UPDATE -> {
|
||||
final String updateAvatarObjectName = ProfileHelper.generateAvatarObjectName();
|
||||
yield new AvatarData(currentAvatar, Optional.of(updateAvatarObjectName),
|
||||
Optional.of(generateAvatarUploadForm(updateAvatarObjectName)));
|
||||
Optional.of(ProfileGrpcHelper.generateAvatarUploadForm(updateAvatarObjectName, ProfileHelper.MAX_PROFILE_AVATAR_SIZE_BYTES, policyGenerator, clock)));
|
||||
}
|
||||
};
|
||||
|
||||
@@ -207,6 +218,39 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
|
||||
.build());
|
||||
}
|
||||
|
||||
@Override
|
||||
public GetAvatarCredentialsResponse getAvatarCredentials(final GetAvatarCredentialsRequest request) {
|
||||
|
||||
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
|
||||
|
||||
final Account account = accountsManager.getByAccountIdentifier(authenticatedDevice.accountIdentifier())
|
||||
.orElseThrow(() -> GrpcExceptions.invalidCredentials("account not found"));
|
||||
|
||||
if (account.getZkCredentialKey().isEmpty()) {
|
||||
return GetAvatarCredentialsResponse.newBuilder()
|
||||
.setMissingZkCredentialKey(FailedPrecondition.newBuilder().setDescription("account requires ZK credential key"))
|
||||
.build();
|
||||
}
|
||||
|
||||
try {
|
||||
final AvatarUploadCredentialRequest credentialRequest = new AvatarUploadCredentialRequest(
|
||||
request.getAvatarCredentialsRequest().toByteArray());
|
||||
|
||||
final AvatarUploadCredentialResponse credentialResponse = credentialRequest.issueCredential(
|
||||
new ServiceId.Aci(account.getIdentifier(IdentityType.ACI)),
|
||||
account.getZkCredentialKey().get(),
|
||||
Objects.requireNonNull(account.getZkCredentialKeyRotationId()),
|
||||
clock.instant().truncatedTo(ChronoUnit.DAYS),
|
||||
this.genericServerSecretParams);
|
||||
|
||||
return GetAvatarCredentialsResponse.newBuilder()
|
||||
.setAvatarCredentials(ByteString.copyFrom(credentialResponse.serialize()))
|
||||
.build();
|
||||
} catch (InvalidInputException | VerificationFailedException _) {
|
||||
throw GrpcExceptions.invalidArguments("invalid credential request");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public GetUnversionedProfileResponse getUnversionedProfile(final GetUnversionedProfileRequest request) throws RateLimitExceededException {
|
||||
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
|
||||
@@ -216,7 +260,6 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
|
||||
|
||||
return maybeAccount.map(account -> GetUnversionedProfileResponse.newBuilder()
|
||||
.setResult(ProfileGrpcHelper.buildUnversionedProfileResult(targetIdentifier,
|
||||
authenticatedDevice.accountIdentifier(),
|
||||
account,
|
||||
profileBadgeConverter))
|
||||
.build()).orElseGet(() -> GetUnversionedProfileResponse.newBuilder()
|
||||
@@ -265,20 +308,4 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
|
||||
throw GrpcExceptions.invalidArguments("Request must include commitment during migration");
|
||||
}
|
||||
}
|
||||
|
||||
private ProfileAvatarUploadAttributes generateAvatarUploadForm(final String objectName) {
|
||||
final ZonedDateTime now = ZonedDateTime.now(clock);
|
||||
final Pair<String, String> policy = policyGenerator.createFor(now, objectName, ProfileHelper.MAX_PROFILE_AVATAR_SIZE_BYTES);
|
||||
final String signature = policySigner.getSignature(now, policy.second());
|
||||
|
||||
return ProfileAvatarUploadAttributes.newBuilder()
|
||||
.setPath(objectName)
|
||||
.setCredential(policy.first())
|
||||
.setAcl("private")
|
||||
.setAlgorithm("AWS4-HMAC-SHA256")
|
||||
.setDate(now.format(PostPolicyGenerator.AWS_DATE_TIME))
|
||||
.setPolicy(policy.second())
|
||||
.setSignature(ByteString.copyFrom(signature.getBytes()))
|
||||
.build();
|
||||
}
|
||||
}
|
||||
+521
@@ -0,0 +1,521 @@
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil.getClientPlatform;
|
||||
import static org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil.getPayPalLocale;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import com.google.protobuf.Empty;
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.time.Clock;
|
||||
import java.util.Locale;
|
||||
import java.util.Optional;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import org.signal.chat.errors.FailedPrecondition;
|
||||
import org.signal.chat.errors.FailedUnidentifiedAuthorization;
|
||||
import org.signal.chat.errors.FailedZkAuthentication;
|
||||
import org.signal.chat.errors.NotFound;
|
||||
import org.signal.chat.purchase.CreatePayPalPaymentMethodRequest;
|
||||
import org.signal.chat.purchase.CreatePayPalPaymentMethodResponse;
|
||||
import org.signal.chat.purchase.CreatePaymentMethodRequest;
|
||||
import org.signal.chat.purchase.CreatePaymentMethodResponse;
|
||||
import org.signal.chat.purchase.DeleteSubscriberRequest;
|
||||
import org.signal.chat.purchase.DeleteSubscriberResponse;
|
||||
import org.signal.chat.purchase.GetBankMandateRequest;
|
||||
import org.signal.chat.purchase.GetBankMandateResponse;
|
||||
import org.signal.chat.purchase.GetReceiptCredentialsRequest;
|
||||
import org.signal.chat.purchase.GetReceiptCredentialsResponse;
|
||||
import org.signal.chat.purchase.GetSubscriptionInformationRequest;
|
||||
import org.signal.chat.purchase.GetSubscriptionInformationResponse;
|
||||
import org.signal.chat.purchase.PaymentRequired;
|
||||
import org.signal.chat.purchase.SetDefaultPaymentMethodRequest;
|
||||
import org.signal.chat.purchase.SetDefaultPaymentMethodResponse;
|
||||
import org.signal.chat.purchase.SetIapSubscriptionRequest;
|
||||
import org.signal.chat.purchase.SetIapSubscriptionResponse;
|
||||
import org.signal.chat.purchase.SetSubscriptionLevelRequest;
|
||||
import org.signal.chat.purchase.SetSubscriptionLevelResponse;
|
||||
import org.signal.chat.purchase.SimpleSubscriptionsGrpc;
|
||||
import org.signal.chat.purchase.UpdateSubscriberRequest;
|
||||
import org.signal.chat.purchase.UpdateSubscriberResponse;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.VerificationFailedException;
|
||||
import org.signal.libsignal.zkgroup.donation.DonationPermit;
|
||||
import org.whispersystems.textsecuregcm.configuration.SubscriptionConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.SubscriptionLevelConfiguration;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.DonationPermitsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.SubscriberCredentials;
|
||||
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;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.BraintreeManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.CustomerAwareSubscriptionPaymentProcessor;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.GooglePlayBillingManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.ProcessorCustomer;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.StripeManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriberIdCreationNotPermittedException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionChargeFailurePaymentRequiredException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionForbiddenException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInformation;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidArgumentsException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidIdempotencyKeyException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidLevelException;
|
||||
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.SubscriptionReceiptAlreadyRedeemedException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptRequestedForOpenPaymentException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionStatus;
|
||||
|
||||
public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.SubscriptionsImplBase {
|
||||
|
||||
private final Clock clock;
|
||||
private final SubscriptionConfiguration subscriptionConfiguration;
|
||||
private final SubscriptionManager subscriptionManager;
|
||||
private final DonationPermitsManager donationPermitsManager;
|
||||
private final StripeManager stripeManager;
|
||||
private final BraintreeManager braintreeManager;
|
||||
private final GooglePlayBillingManager googlePlayBillingManager;
|
||||
private final AppleAppStoreManager appleAppStoreManager;
|
||||
private final BankMandateTranslator bankMandateTranslator;
|
||||
|
||||
static final String RECEIPT_ISSUED_COUNTER_NAME = MetricsUtil.name(SubscriptionsGrpcService.class, "receiptIssued");
|
||||
static final String PROCESSOR_TAG_NAME = "processor";
|
||||
static final String TYPE_TAG_NAME = "type";
|
||||
private static final String SUBSCRIPTION_TYPE_TAG_NAME = "subscriptionType";
|
||||
|
||||
public SubscriptionsGrpcService(final Clock clock,
|
||||
final SubscriptionConfiguration subscriptionConfiguration,
|
||||
final SubscriptionManager subscriptionManager,
|
||||
final DonationPermitsManager donationPermitsManager,
|
||||
final StripeManager stripeManager,
|
||||
final BraintreeManager braintreeManager,
|
||||
final GooglePlayBillingManager googlePlayBillingManager,
|
||||
final AppleAppStoreManager appleAppStoreManager,
|
||||
final BankMandateTranslator bankMandateTranslator) {
|
||||
this.clock = clock;
|
||||
this.subscriptionConfiguration = subscriptionConfiguration;
|
||||
this.subscriptionManager = subscriptionManager;
|
||||
this.donationPermitsManager = donationPermitsManager;
|
||||
this.stripeManager = stripeManager;
|
||||
this.braintreeManager = braintreeManager;
|
||||
this.googlePlayBillingManager = googlePlayBillingManager;
|
||||
this.appleAppStoreManager = appleAppStoreManager;
|
||||
this.bankMandateTranslator = bankMandateTranslator;
|
||||
}
|
||||
|
||||
@Override
|
||||
public UpdateSubscriberResponse updateSubscriber(final UpdateSubscriberRequest request) {
|
||||
|
||||
try {
|
||||
final SubscriberCredentials subscriberCredentials = SubscriberCredentials.process(
|
||||
request.getSubscriberId().toByteArray(), clock);
|
||||
|
||||
final boolean creationPermitted;
|
||||
try {
|
||||
if (request.getDonationPermit().isEmpty()) {
|
||||
creationPermitted = false;
|
||||
} else {
|
||||
final DonationPermit permit = new DonationPermit(request.getDonationPermit().toByteArray());
|
||||
|
||||
creationPermitted = SubscriptionsUtil.verifyAndSpendDonationPermit(permit, donationPermitsManager, clock);
|
||||
}
|
||||
} catch (final InvalidInputException _) {
|
||||
throw GrpcExceptions.invalidArguments("invalid donation permit");
|
||||
} catch (final VerificationFailedException _) {
|
||||
return UpdateSubscriberResponse.newBuilder()
|
||||
.setPermitRejected(FailedZkAuthentication.newBuilder()
|
||||
.setDescription("donation permit failed verification")
|
||||
.build())
|
||||
.build();
|
||||
}
|
||||
|
||||
subscriptionManager.updateSubscriber(subscriberCredentials, creationPermitted);
|
||||
return UpdateSubscriberResponse.newBuilder().setSuccess(Empty.getDefaultInstance()).build();
|
||||
} catch (final SubscriptionForbiddenException e) {
|
||||
return UpdateSubscriberResponse.newBuilder().setSubscriberIdMismatch(
|
||||
FailedUnidentifiedAuthorization.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
|
||||
} catch (SubscriberIdCreationNotPermittedException _) {
|
||||
if (request.getDonationPermit().isEmpty()) {
|
||||
throw GrpcExceptions.invalidArguments("donation permit is required to create a subscriber ID");
|
||||
}
|
||||
|
||||
return UpdateSubscriberResponse.newBuilder()
|
||||
.setPermitRejected(FailedZkAuthentication.newBuilder()
|
||||
.setDescription("donation permit was not valid")
|
||||
.build())
|
||||
.build();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public DeleteSubscriberResponse deleteSubscriber(final DeleteSubscriberRequest request)
|
||||
throws RateLimitExceededException {
|
||||
try {
|
||||
final SubscriberCredentials subscriberCredentials = SubscriberCredentials.process(
|
||||
request.getSubscriberId().toByteArray(), clock);
|
||||
subscriptionManager.deleteSubscriber(subscriberCredentials);
|
||||
return DeleteSubscriberResponse.newBuilder().setSuccess(Empty.getDefaultInstance()).build();
|
||||
} catch (final SubscriptionNotFoundException e) {
|
||||
return DeleteSubscriberResponse.newBuilder().setSubscriberNotFound(NotFound.newBuilder().build()).build();
|
||||
} catch (final SubscriptionInvalidArgumentsException e) {
|
||||
return DeleteSubscriberResponse.newBuilder().setCannotCancelSubscription(
|
||||
FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public CreatePaymentMethodResponse createPaymentMethod(final CreatePaymentMethodRequest request) {
|
||||
final SubscriberCredentials subscriberCredentials = SubscriberCredentials.process(
|
||||
request.getSubscriberId().toByteArray(), clock);
|
||||
final CustomerAwareSubscriptionPaymentProcessor customerAwareSubscriptionPaymentProcessor = switch (request.getPaymentMethod()) {
|
||||
case PAYMENT_METHOD_CARD, PAYMENT_METHOD_SEPA_DEBIT, PAYMENT_METHOD_IDEAL -> stripeManager;
|
||||
default -> throw GrpcExceptions.fieldViolation("payment_method", "Unsupported payment method");
|
||||
};
|
||||
|
||||
try {
|
||||
final DonationPermit permit = new DonationPermit(request.getDonationPermit().toByteArray());
|
||||
|
||||
if (!SubscriptionsUtil.verifyAndSpendDonationPermit(permit, donationPermitsManager, clock)) {
|
||||
return CreatePaymentMethodResponse.newBuilder()
|
||||
.setPermitRejected(FailedZkAuthentication.getDefaultInstance())
|
||||
.build();
|
||||
}
|
||||
} catch (final InvalidInputException _) {
|
||||
throw GrpcExceptions.invalidArguments("invalid donation permit");
|
||||
} catch (final VerificationFailedException _) {
|
||||
return CreatePaymentMethodResponse.newBuilder()
|
||||
.setPermitRejected(FailedZkAuthentication.getDefaultInstance())
|
||||
.build();
|
||||
}
|
||||
|
||||
try {
|
||||
final String token = subscriptionManager.addPaymentMethodToCustomer(subscriberCredentials,
|
||||
customerAwareSubscriptionPaymentProcessor,
|
||||
getClientPlatform(RequestAttributesUtil.getUserAgent().orElse(null)),
|
||||
CustomerAwareSubscriptionPaymentProcessor::createPaymentMethodSetupToken);
|
||||
return CreatePaymentMethodResponse.newBuilder().setResult(
|
||||
CreatePaymentMethodResponse.CreatePaymentMethodResult.newBuilder().setClientSecret(token)
|
||||
.setPaymentProvider(customerAwareSubscriptionPaymentProcessor.getProvider().toProto()).build()).build();
|
||||
} catch (final SubscriptionNotFoundException e) {
|
||||
return CreatePaymentMethodResponse.newBuilder().setSubscriberNotFound(NotFound.newBuilder()).build();
|
||||
} catch (final SubscriptionForbiddenException e) {
|
||||
return CreatePaymentMethodResponse.newBuilder().setSubscriberIdMismatch(
|
||||
FailedUnidentifiedAuthorization.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
|
||||
} catch (final SubscriptionProcessorConflictException e) {
|
||||
return CreatePaymentMethodResponse.newBuilder().setSubscriptionProcessorConflict(
|
||||
FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public CreatePayPalPaymentMethodResponse createPayPalPaymentMethod(final CreatePayPalPaymentMethodRequest request)
|
||||
throws IOException {
|
||||
final SubscriberCredentials subscriberCredentials = SubscriberCredentials.process(
|
||||
request.getSubscriberId().toByteArray(), clock);
|
||||
final Locale locale = getPayPalLocale(RequestAttributesUtil.getAvailableAcceptedLocales());
|
||||
try {
|
||||
final BraintreeManager.PayPalBillingAgreementApprovalDetails details = subscriptionManager.addPaymentMethodToCustomer(
|
||||
subscriberCredentials, braintreeManager, getClientPlatform(RequestAttributesUtil.getUserAgent().orElse(null)),
|
||||
(mgr, _) -> mgr.createPayPalBillingAgreement(request.getReturnUrl(), request.getCancelUrl(),
|
||||
locale.toLanguageTag()));
|
||||
return CreatePayPalPaymentMethodResponse.newBuilder().setResult(
|
||||
CreatePayPalPaymentMethodResponse.CreatePayPalPaymentMethodResult.newBuilder()
|
||||
.setApprovalUrl(details.approvalUrl()).setToken(details.billingAgreementToken()).build()).build();
|
||||
} catch (final SubscriptionNotFoundException e) {
|
||||
return CreatePayPalPaymentMethodResponse.newBuilder().setSubscriberNotFound(NotFound.newBuilder().build())
|
||||
.build();
|
||||
} catch (final SubscriptionForbiddenException e) {
|
||||
return CreatePayPalPaymentMethodResponse.newBuilder().setSubscriberIdMismatch(
|
||||
FailedUnidentifiedAuthorization.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
|
||||
} catch (final SubscriptionProcessorConflictException e) {
|
||||
return CreatePayPalPaymentMethodResponse.newBuilder().setSubscriptionProcessorConflict(
|
||||
FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public SetDefaultPaymentMethodResponse setDefaultPaymentMethod(final SetDefaultPaymentMethodRequest request)
|
||||
throws IOException {
|
||||
try {
|
||||
final SubscriberCredentials subscriberCredentials = SubscriberCredentials.process(
|
||||
request.getSubscriberId().toByteArray(), clock);
|
||||
final CustomerAwareSubscriptionPaymentProcessor manager;
|
||||
final String paymentMethodId = switch (request.getRequestCase()) {
|
||||
case STRIPE -> {
|
||||
manager = stripeManager;
|
||||
yield request.getStripe().getPaymentMethodToken();
|
||||
}
|
||||
case BRAINTREE -> {
|
||||
manager = braintreeManager;
|
||||
yield request.getBraintree().getPaymentMethodToken();
|
||||
}
|
||||
case SEPA -> {
|
||||
manager = stripeManager;
|
||||
yield stripeManager.getGeneratedSepaIdFromSetupIntent(request.getSepa().getSetupIntentId());
|
||||
}
|
||||
default -> throw GrpcExceptions.fieldViolation("request", "No payment method specified");
|
||||
};
|
||||
|
||||
final Subscriptions.Record record = subscriptionManager.getSubscriber(subscriberCredentials);
|
||||
return record.getProcessorCustomer().map(
|
||||
processorCustomer -> setDefaultPaymentMethodForCustomer(manager, processorCustomer, paymentMethodId,
|
||||
record.subscriptionId)).orElseGet(() ->
|
||||
// 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
|
||||
SetDefaultPaymentMethodResponse.newBuilder().setPaymentMethodNotSetUp(FailedPrecondition.newBuilder().build())
|
||||
.build());
|
||||
} catch (final SubscriptionNotFoundException e) {
|
||||
return SetDefaultPaymentMethodResponse.newBuilder().setSubscriberNotFound(NotFound.newBuilder().build()).build();
|
||||
} catch (final SubscriptionForbiddenException e) {
|
||||
return SetDefaultPaymentMethodResponse.newBuilder().setSubscriberIdMismatch(
|
||||
FailedUnidentifiedAuthorization.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
|
||||
} catch (final SubscriptionProcessorConflictException e) {
|
||||
return SetDefaultPaymentMethodResponse.newBuilder()
|
||||
.setSubscriptionProcessorConflict(
|
||||
FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
|
||||
}
|
||||
}
|
||||
|
||||
private static SetDefaultPaymentMethodResponse setDefaultPaymentMethodForCustomer(
|
||||
final CustomerAwareSubscriptionPaymentProcessor processor, final ProcessorCustomer processorCustomer,
|
||||
final String paymentMethodId, final String subscriptionId) {
|
||||
try {
|
||||
processor.setDefaultPaymentMethodForCustomer(processorCustomer.customerId(), paymentMethodId, subscriptionId);
|
||||
return SetDefaultPaymentMethodResponse.newBuilder().setSuccess(Empty.getDefaultInstance()).build();
|
||||
} catch (final 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
|
||||
return SetDefaultPaymentMethodResponse.newBuilder()
|
||||
.setPaymentMethodNotSetUp(FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build())
|
||||
.build();
|
||||
} catch (final IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public SetSubscriptionLevelResponse setSubscriptionLevel(final SetSubscriptionLevelRequest request) {
|
||||
final SubscriberCredentials subscriberCredentials = SubscriberCredentials.process(
|
||||
request.getSubscriberId().toByteArray(), clock);
|
||||
try {
|
||||
final Subscriptions.Record record = subscriptionManager.getSubscriber(subscriberCredentials);
|
||||
return record.getProcessorCustomer().map(
|
||||
processorCustomer -> setSubscriptionLevelForCustomer(processorCustomer, subscriberCredentials, record,
|
||||
request)).orElseGet(() -> SetSubscriptionLevelResponse.newBuilder()
|
||||
.setPaymentMethodNotSetUp(FailedPrecondition.newBuilder().build()).build());
|
||||
|
||||
} catch (final SubscriptionNotFoundException e) {
|
||||
return SetSubscriptionLevelResponse.newBuilder().setSubscriberNotFound(NotFound.newBuilder().build()).build();
|
||||
} catch (final SubscriptionForbiddenException e) {
|
||||
return SetSubscriptionLevelResponse.newBuilder().setSubscriberIdMismatch(
|
||||
FailedUnidentifiedAuthorization.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
|
||||
}
|
||||
}
|
||||
|
||||
private SetSubscriptionLevelResponse setSubscriptionLevelForCustomer(final ProcessorCustomer processorCustomer,
|
||||
final SubscriberCredentials subscriberCredentials, final Subscriptions.Record subscriptionRecord,
|
||||
final SetSubscriptionLevelRequest request) {
|
||||
final SubscriptionLevelConfiguration config = subscriptionConfiguration.getSubscriptionLevel(request.getLevel());
|
||||
if (config == null) {
|
||||
return SetSubscriptionLevelResponse.newBuilder().setUnsupportedLevel(FailedPrecondition.newBuilder().build())
|
||||
.build();
|
||||
}
|
||||
final Optional<String> templateId = Optional.ofNullable(
|
||||
config.prices().get(request.getCurrency().toLowerCase(Locale.ROOT)))
|
||||
.map(priceConfiguration -> priceConfiguration.processorIds().get(processorCustomer.processor()));
|
||||
if (templateId.isEmpty()) {
|
||||
return SetSubscriptionLevelResponse.newBuilder().setUnsupportedCurrency(FailedPrecondition.newBuilder().build())
|
||||
.build();
|
||||
}
|
||||
|
||||
final CustomerAwareSubscriptionPaymentProcessor manager;
|
||||
switch (processorCustomer.processor()) {
|
||||
case STRIPE -> manager = stripeManager;
|
||||
case BRAINTREE -> manager = braintreeManager;
|
||||
default -> {
|
||||
return SetSubscriptionLevelResponse.newBuilder().setUnsupportedOperation(FailedPrecondition.newBuilder()
|
||||
.setDescription(
|
||||
"Operation cannot be performed with the '" + processorCustomer.processor() + "' payment provider")
|
||||
.build()).build();
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
subscriptionManager.updateSubscriptionLevelForCustomer(subscriberCredentials, subscriptionRecord, manager,
|
||||
request.getLevel(), request.getCurrency(), request.getIdempotencyKey(), templateId.get(),
|
||||
(l1, l2) -> SubscriptionsUtil.subscriptionsAreSameType(subscriptionConfiguration, l1, l2));
|
||||
return SetSubscriptionLevelResponse.newBuilder().setSuccess(
|
||||
SetSubscriptionLevelResponse.SetSubscriptionLevelResult.newBuilder().setLevel(request.getLevel()).build())
|
||||
.build();
|
||||
} catch (final SubscriptionInvalidIdempotencyKeyException e) {
|
||||
return SetSubscriptionLevelResponse.newBuilder()
|
||||
.setInvalidIdempotencyKey(FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build())
|
||||
.build();
|
||||
} catch (final SubscriptionProcessorException e) {
|
||||
return SetSubscriptionLevelResponse.newBuilder()
|
||||
.setChargeFailure(SubscriptionsUtil.toChargeFailure(e.getProcessor(), e.getChargeFailure())).build();
|
||||
} catch (final SubscriptionPaymentRequiresActionException e) {
|
||||
return SetSubscriptionLevelResponse.newBuilder().setPaymentRequiresAction(FailedPrecondition.newBuilder().build())
|
||||
.build();
|
||||
} catch (final SubscriptionInvalidLevelException e) {
|
||||
return SetSubscriptionLevelResponse.newBuilder()
|
||||
.setInvalidLevelTransition(FailedPrecondition.newBuilder().build()).build();
|
||||
} catch (final SubscriptionProcessorConflictException e) {
|
||||
return SetSubscriptionLevelResponse.newBuilder().setSubscriptionProcessorConflict(
|
||||
FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public SetIapSubscriptionResponse setIapSubscription(final SetIapSubscriptionRequest request)
|
||||
throws RateLimitExceededException {
|
||||
final SubscriberCredentials subscriberCredentials = SubscriberCredentials.process(
|
||||
request.getSubscriberId().toByteArray(), clock);
|
||||
try {
|
||||
final long level = switch (request.getRequestCase()) {
|
||||
case APP_STORE -> subscriptionManager.updateAppStoreTransactionId(subscriberCredentials, appleAppStoreManager,
|
||||
request.getAppStore().getOriginalTransactionId());
|
||||
case PLAY_BILLING ->
|
||||
subscriptionManager.updatePlayBillingPurchaseToken(subscriberCredentials, googlePlayBillingManager,
|
||||
request.getPlayBilling().getPurchaseToken());
|
||||
default -> throw GrpcExceptions.fieldViolation("request", "must set request type");
|
||||
};
|
||||
return SetIapSubscriptionResponse.newBuilder()
|
||||
.setSuccess(SetIapSubscriptionResponse.SetIapSubscriptionResult.newBuilder().setLevel(level).build()).build();
|
||||
} catch (final SubscriptionNotFoundException e) {
|
||||
return SetIapSubscriptionResponse.newBuilder().setSubscriberNotFound(NotFound.newBuilder().build()).build();
|
||||
} catch (final SubscriptionForbiddenException e) {
|
||||
return SetIapSubscriptionResponse.newBuilder().setSubscriberIdMismatch(
|
||||
FailedUnidentifiedAuthorization.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
|
||||
} catch (final SubscriptionProcessorConflictException e) {
|
||||
return SetIapSubscriptionResponse.newBuilder().setSubscriptionProcessorConflict(
|
||||
FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
|
||||
} catch (final SubscriptionPaymentRequiredException e) {
|
||||
return SetIapSubscriptionResponse.newBuilder().setPaymentRequired(FailedPrecondition.newBuilder().build())
|
||||
.build();
|
||||
} catch (final SubscriptionInvalidArgumentsException e) {
|
||||
return SetIapSubscriptionResponse.newBuilder()
|
||||
.setInvalidTransaction(FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public GetSubscriptionInformationResponse getSubscriptionInformation(final GetSubscriptionInformationRequest request)
|
||||
throws RateLimitExceededException {
|
||||
final SubscriberCredentials subscriberCredentials = SubscriberCredentials.process(
|
||||
request.getSubscriberId().toByteArray(), clock);
|
||||
try {
|
||||
return subscriptionManager.getSubscriptionInformation(subscriberCredentials)
|
||||
.map(SubscriptionsGrpcService::buildSubscriptionInformationResponse).orElseGet(
|
||||
() -> GetSubscriptionInformationResponse.newBuilder().setNoSubscription(Empty.getDefaultInstance())
|
||||
.build());
|
||||
} catch (final SubscriptionNotFoundException e) {
|
||||
return GetSubscriptionInformationResponse.newBuilder().setSubscriberNotFound(NotFound.newBuilder().build())
|
||||
.build();
|
||||
} catch (final SubscriptionForbiddenException e) {
|
||||
return GetSubscriptionInformationResponse.newBuilder().setSubscriberIdMismatch(
|
||||
FailedUnidentifiedAuthorization.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
|
||||
}
|
||||
}
|
||||
|
||||
private static GetSubscriptionInformationResponse buildSubscriptionInformationResponse(
|
||||
final SubscriptionInformation info) {
|
||||
|
||||
final GetSubscriptionInformationResponse.Subscription.Builder subscription = GetSubscriptionInformationResponse.Subscription.newBuilder()
|
||||
.setLevel(info.level()).setEndOfCurrentPeriod(info.endOfCurrentPeriod().getEpochSecond())
|
||||
.setActive(info.active()).setCancelAtPeriodEnd(info.cancelAtPeriodEnd()).setCurrency(info.price().currency())
|
||||
.setAmount(info.price().amount().longValue()).setStatus(toProtoSubscriptionStatus(info.status()))
|
||||
.setProcessor(info.paymentProvider().toProto()).setPaymentMethod(info.paymentMethod().toProtoPaymentMethod())
|
||||
.setPaymentProcessing(info.paymentProcessing());
|
||||
if (info.billingCycleAnchor() != null) {
|
||||
subscription.setBillingCycleAnchor(info.billingCycleAnchor().getEpochSecond());
|
||||
}
|
||||
if (info.chargeFailure() != null) {
|
||||
subscription.setChargeFailure(SubscriptionsUtil.toChargeFailure(info.paymentProvider(), info.chargeFailure()));
|
||||
}
|
||||
return GetSubscriptionInformationResponse.newBuilder().setSuccess(subscription.build()).build();
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public GetReceiptCredentialsResponse getReceiptCredentials(final GetReceiptCredentialsRequest request)
|
||||
throws RateLimitExceededException {
|
||||
final SubscriberCredentials subscriberCredentials = SubscriberCredentials.process(
|
||||
request.getSubscriberId().toByteArray(), clock);
|
||||
try {
|
||||
final SubscriptionManager.ReceiptResult result = subscriptionManager.createReceiptCredentials(
|
||||
subscriberCredentials, request.getReceiptCredentialRequest().toByteArray(),
|
||||
r -> SubscriptionsUtil.receiptExpirationWithGracePeriod(subscriptionConfiguration, r));
|
||||
Metrics.counter(RECEIPT_ISSUED_COUNTER_NAME,
|
||||
Tags.of(
|
||||
Tag.of(PROCESSOR_TAG_NAME, result.paymentProvider().toString()),
|
||||
Tag.of(TYPE_TAG_NAME, "subscription"),
|
||||
Tag.of(SUBSCRIPTION_TYPE_TAG_NAME,
|
||||
subscriptionConfiguration.getSubscriptionLevel(result.receiptItem().level()).type().name()
|
||||
.toLowerCase(Locale.ROOT)),
|
||||
UserAgentTagUtil.getPlatformTag(RequestAttributesUtil.getUserAgent().orElse(null))))
|
||||
.increment();
|
||||
return GetReceiptCredentialsResponse.newBuilder().setSuccess(
|
||||
GetReceiptCredentialsResponse.GetReceiptCredentialsResult.newBuilder()
|
||||
.setReceiptCredentialResponse(ByteString.copyFrom(result.receiptCredentialResponse().serialize()))
|
||||
.build()).build();
|
||||
} catch (final SubscriptionReceiptRequestedForOpenPaymentException e) {
|
||||
return GetReceiptCredentialsResponse.newBuilder().setNoPaidInvoice(FailedPrecondition.newBuilder().build())
|
||||
.build();
|
||||
} catch (final SubscriptionChargeFailurePaymentRequiredException e) {
|
||||
return GetReceiptCredentialsResponse.newBuilder().setPaymentRequired(
|
||||
PaymentRequired.newBuilder()
|
||||
.setChargeFailure(SubscriptionsUtil.toChargeFailure(e.getProcessor(), e.getChargeFailure())).build()).build();
|
||||
} catch (final SubscriptionPaymentRequiredException e) {
|
||||
return GetReceiptCredentialsResponse.newBuilder()
|
||||
.setPaymentRequired(PaymentRequired.newBuilder().build()).build();
|
||||
} catch (final SubscriptionInvalidArgumentsException e) {
|
||||
throw GrpcExceptions.invalidArguments(e.errorDetail().orElse(""));
|
||||
} catch (final SubscriptionReceiptAlreadyRedeemedException e) {
|
||||
return GetReceiptCredentialsResponse.newBuilder().setAlreadyRedeemed(FailedPrecondition.newBuilder().build())
|
||||
.build();
|
||||
} catch (final SubscriptionNotFoundException e) {
|
||||
return GetReceiptCredentialsResponse.newBuilder().setSubscriberNotFound(NotFound.newBuilder().build()).build();
|
||||
} catch (final SubscriptionForbiddenException e) {
|
||||
return GetReceiptCredentialsResponse.newBuilder().setSubscriberIdMismatch(
|
||||
FailedUnidentifiedAuthorization.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
|
||||
}
|
||||
}
|
||||
|
||||
private static org.signal.chat.purchase.SubscriptionStatus toProtoSubscriptionStatus(
|
||||
final SubscriptionStatus status) {
|
||||
return switch (status) {
|
||||
case ACTIVE -> org.signal.chat.purchase.SubscriptionStatus.SUBSCRIPTION_STATUS_ACTIVE;
|
||||
case INCOMPLETE -> org.signal.chat.purchase.SubscriptionStatus.SUBSCRIPTION_STATUS_INCOMPLETE;
|
||||
case PAST_DUE -> org.signal.chat.purchase.SubscriptionStatus.SUBSCRIPTION_STATUS_PAST_DUE;
|
||||
case CANCELED -> org.signal.chat.purchase.SubscriptionStatus.SUBSCRIPTION_STATUS_CANCELED;
|
||||
case UNPAID -> org.signal.chat.purchase.SubscriptionStatus.SUBSCRIPTION_STATUS_UNPAID;
|
||||
case UNKNOWN -> org.signal.chat.purchase.SubscriptionStatus.SUBSCRIPTION_STATUS_UNKNOWN;
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public GetBankMandateResponse getBankMandate(final GetBankMandateRequest request) {
|
||||
final BankTransferType bankTransferType = switch (request.getBankTransferType()) {
|
||||
case BANK_TRANSFER_TYPE_SEPA_DEBIT -> BankTransferType.SEPA_DEBIT;
|
||||
default -> throw GrpcExceptions.fieldViolation("bank_transfer_type", "Unsupported bank transfer type");
|
||||
};
|
||||
final String mandate = bankMandateTranslator.translate(RequestAttributesUtil.getAvailableAcceptedLocales(),
|
||||
bankTransferType);
|
||||
return GetBankMandateResponse.newBuilder().setMandate(mandate).build();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import java.math.BigDecimal;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
import javax.annotation.Nullable;
|
||||
import org.signal.libsignal.zkgroup.VerificationFailedException;
|
||||
import org.signal.libsignal.zkgroup.donation.DonationPermit;
|
||||
import org.whispersystems.textsecuregcm.badges.BadgeTranslator;
|
||||
import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.OneTimeDonationCurrencyConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.SubscriptionConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.SubscriptionLevelConfiguration;
|
||||
import org.whispersystems.textsecuregcm.entities.Badge;
|
||||
import org.whispersystems.textsecuregcm.entities.PurchasableBadge;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.DonationPermitsManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.ChargeFailure;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.CurrencyConfiguration;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.CustomerAwareSubscriptionPaymentProcessor;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.LevelConfiguration;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentMethod;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
|
||||
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
|
||||
import org.whispersystems.textsecuregcm.util.ua.UnrecognizedUserAgentException;
|
||||
import org.whispersystems.textsecuregcm.util.ua.UserAgentUtil;
|
||||
|
||||
public class SubscriptionsUtil {
|
||||
|
||||
private static final String DONATION_PERMIT_PRESENT_COUNTER_NAME = MetricsUtil.name(SubscriptionsUtil.class,
|
||||
"donationPermitPresent");
|
||||
|
||||
private static final String DONATION_PERMIT_SPEND_COUNTER_NAME = MetricsUtil.name(SubscriptionsUtil.class,
|
||||
"donationPermitSpend");
|
||||
|
||||
@Nullable
|
||||
public static ClientPlatform getClientPlatform(@Nullable final String userAgentString) {
|
||||
try {
|
||||
return UserAgentUtil.parseUserAgentString(userAgentString).platform();
|
||||
} catch (final UnrecognizedUserAgentException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean subscriptionsAreSameType(final SubscriptionConfiguration subscriptionConfiguration, final long level1, final long level2) {
|
||||
return subscriptionConfiguration.getSubscriptionLevel(level1).type()
|
||||
== subscriptionConfiguration.getSubscriptionLevel(level2).type();
|
||||
}
|
||||
|
||||
public static Instant receiptExpirationWithGracePeriod(
|
||||
final SubscriptionConfiguration subscriptionConfiguration,
|
||||
final CustomerAwareSubscriptionPaymentProcessor.ReceiptItem receiptItem) {
|
||||
return switch (subscriptionConfiguration.getSubscriptionLevel(receiptItem.level()).type()) {
|
||||
case DONATION -> receiptItem.paymentTime().receiptExpiration(
|
||||
subscriptionConfiguration.getBadgeExpiration(),
|
||||
subscriptionConfiguration.getBadgeGracePeriod());
|
||||
case BACKUP -> receiptItem.paymentTime().receiptExpiration(
|
||||
subscriptionConfiguration.getBackupExpiration(),
|
||||
subscriptionConfiguration.getBackupGracePeriod());
|
||||
};
|
||||
}
|
||||
|
||||
public static Map<String, CurrencyConfiguration> buildCurrencyConfiguration(final List<CustomerAwareSubscriptionPaymentProcessor> subscriptionPaymentProcessors,
|
||||
final OneTimeDonationConfiguration oneTimeDonationConfiguration,
|
||||
final SubscriptionConfiguration subscriptionConfiguration) {
|
||||
return oneTimeDonationConfiguration.currencies()
|
||||
.entrySet().stream()
|
||||
.collect(Collectors.toMap(Map.Entry::getKey, currencyAndConfig -> {
|
||||
final String currency = currencyAndConfig.getKey();
|
||||
final OneTimeDonationCurrencyConfiguration currencyConfig = currencyAndConfig.getValue();
|
||||
|
||||
final Map<Long, List<BigDecimal>> oneTimeLevelsToSuggestedAmounts = Map.of(
|
||||
oneTimeDonationConfiguration.boost().level(), currencyConfig.boosts(),
|
||||
oneTimeDonationConfiguration.gift().level(), List.of(currencyConfig.gift())
|
||||
);
|
||||
|
||||
final Function<Map<Long, ? extends SubscriptionLevelConfiguration>, Map<Long, BigDecimal>> extractSubscriptionAmounts = levels ->
|
||||
levels.entrySet().stream()
|
||||
.filter(levelIdAndConfig -> levelIdAndConfig.getValue().prices().containsKey(currency))
|
||||
.collect(Collectors.toMap(
|
||||
Map.Entry::getKey,
|
||||
levelIdAndConfig -> levelIdAndConfig.getValue().prices().get(currency).amount()));
|
||||
|
||||
final List<PaymentMethod> supportedPaymentMethods = Arrays.stream(PaymentMethod.values())
|
||||
.filter(paymentMethod -> subscriptionPaymentProcessors.stream()
|
||||
.anyMatch(manager -> manager.supportsPaymentMethod(paymentMethod)
|
||||
&& manager.getSupportedCurrenciesForPaymentMethod(paymentMethod).contains(currency)))
|
||||
.collect(Collectors.toList());
|
||||
|
||||
if (supportedPaymentMethods.isEmpty()) {
|
||||
throw new RuntimeException("Configuration has currency with no processor support: " + currency);
|
||||
}
|
||||
|
||||
return new CurrencyConfiguration(
|
||||
currencyConfig.minimum(),
|
||||
oneTimeLevelsToSuggestedAmounts,
|
||||
extractSubscriptionAmounts.apply(subscriptionConfiguration.getDonationLevels()),
|
||||
extractSubscriptionAmounts.apply(subscriptionConfiguration.getBackupLevels()),
|
||||
supportedPaymentMethods);
|
||||
}));
|
||||
}
|
||||
|
||||
public static Map<Long, LevelConfiguration> buildDonationLevelsConfiguration(
|
||||
final SubscriptionConfiguration subscriptionConfiguration,
|
||||
final OneTimeDonationConfiguration oneTimeDonationConfiguration,
|
||||
final BadgeTranslator badgeTranslator,
|
||||
final List<Locale> acceptableLanguages) {
|
||||
final Map<Long, LevelConfiguration> donationLevels = new HashMap<>();
|
||||
|
||||
subscriptionConfiguration.getDonationLevels().forEach((levelId, levelConfig) -> {
|
||||
final LevelConfiguration levelConfiguration = new LevelConfiguration(
|
||||
badgeTranslator.translate(acceptableLanguages, levelConfig.badge()));
|
||||
donationLevels.put(levelId, levelConfiguration);
|
||||
});
|
||||
|
||||
final Badge boostBadge = badgeTranslator.translate(acceptableLanguages,
|
||||
oneTimeDonationConfiguration.boost().badge());
|
||||
donationLevels.put(oneTimeDonationConfiguration.boost().level(),
|
||||
new LevelConfiguration(
|
||||
// NB: the one-time badges are PurchasableBadge, which has a `duration` field
|
||||
new PurchasableBadge(
|
||||
boostBadge,
|
||||
oneTimeDonationConfiguration.boost().expiration())));
|
||||
|
||||
final Badge giftBadge = badgeTranslator.translate(acceptableLanguages, oneTimeDonationConfiguration.gift().badge());
|
||||
donationLevels.put(oneTimeDonationConfiguration.gift().level(),
|
||||
new LevelConfiguration(
|
||||
new PurchasableBadge(
|
||||
giftBadge,
|
||||
oneTimeDonationConfiguration.gift().expiration())));
|
||||
return donationLevels;
|
||||
}
|
||||
|
||||
/// Verifies the permit and spends it
|
||||
///
|
||||
/// @return `true` if the spend was accepted, otherwise `false`
|
||||
/// @throws VerificationFailedException if the permit is invalid
|
||||
public static boolean verifyAndSpendDonationPermit(final DonationPermit permit, final DonationPermitsManager donationPermitsManager, final Clock clock) throws VerificationFailedException {
|
||||
|
||||
final boolean spent = donationPermitsManager.spend(permit);
|
||||
|
||||
Metrics.counter(DONATION_PERMIT_SPEND_COUNTER_NAME, "outcome", spent ? "success" : "failure").increment();
|
||||
|
||||
return spent;
|
||||
}
|
||||
|
||||
public static void recordDonationPermitPresent(final boolean present, final String context, final String userAgent) {
|
||||
Metrics.counter(DONATION_PERMIT_PRESENT_COUNTER_NAME,
|
||||
Tags.of("present", String.valueOf(present),
|
||||
"context", context)
|
||||
.and(UserAgentTagUtil.getPlatformTag(userAgent)))
|
||||
.increment();
|
||||
}
|
||||
|
||||
public static org.signal.chat.purchase.ChargeFailure toChargeFailure(final PaymentProvider processor,
|
||||
final ChargeFailure chargeFailure) {
|
||||
final org.signal.chat.purchase.ChargeFailure.Builder builder = org.signal.chat.purchase.ChargeFailure.newBuilder()
|
||||
.setProcessor(processor.toProto()).setCode(chargeFailure.code()).setMessage(chargeFailure.message());
|
||||
if (chargeFailure.outcomeNetworkStatus() != null) {
|
||||
builder.setOutcomeNetworkStatus(chargeFailure.outcomeNetworkStatus());
|
||||
}
|
||||
if (chargeFailure.outcomeReason() != null) {
|
||||
builder.setOutcomeReason(chargeFailure.outcomeReason());
|
||||
}
|
||||
if (chargeFailure.outcomeType() != null) {
|
||||
builder.setOutcomeType(chargeFailure.outcomeType());
|
||||
}
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
public static Locale getPayPalLocale(final List<Locale> acceptableLocales) {
|
||||
return acceptableLocales.stream()
|
||||
.filter(l -> !"*".equals(l.getLanguage()))
|
||||
.findFirst()
|
||||
.orElse(Locale.US);
|
||||
}
|
||||
}
|
||||
+109
-52
@@ -12,17 +12,19 @@ import io.grpc.Metadata;
|
||||
import io.grpc.ServerCall;
|
||||
import io.grpc.ServerCallHandler;
|
||||
import io.grpc.ServerInterceptor;
|
||||
import io.grpc.Status;
|
||||
import io.grpc.StatusRuntimeException;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import org.signal.chat.require.ElementConstraint;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.grpc.validators.Base64UrlFieldValidator;
|
||||
import org.whispersystems.textsecuregcm.grpc.validators.FieldValidator;
|
||||
import org.whispersystems.textsecuregcm.grpc.validators.E164FieldValidator;
|
||||
import org.whispersystems.textsecuregcm.grpc.validators.EnumSpecifiedFieldValidator;
|
||||
import org.whispersystems.textsecuregcm.grpc.validators.ExactlySizeFieldValidator;
|
||||
import org.whispersystems.textsecuregcm.grpc.validators.FieldValidationException;
|
||||
import org.whispersystems.textsecuregcm.grpc.validators.FieldValidator;
|
||||
import org.whispersystems.textsecuregcm.grpc.validators.NonEmptyFieldValidator;
|
||||
import org.whispersystems.textsecuregcm.grpc.validators.PresentFieldValidator;
|
||||
import org.whispersystems.textsecuregcm.grpc.validators.RangeFieldValidator;
|
||||
@@ -32,17 +34,22 @@ import org.whispersystems.textsecuregcm.grpc.validators.SizeFieldValidator;
|
||||
public class ValidatingInterceptor implements ServerInterceptor {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(ValidatingInterceptor.class);
|
||||
private final Map<String, FieldValidator> fieldValidators = Map.of(
|
||||
"org.signal.chat.require.nonEmpty", new NonEmptyFieldValidator(),
|
||||
"org.signal.chat.require.present", new PresentFieldValidator(),
|
||||
"org.signal.chat.require.specified", new EnumSpecifiedFieldValidator(),
|
||||
"org.signal.chat.require.e164", new E164FieldValidator(),
|
||||
"org.signal.chat.require.exactlySize", new ExactlySizeFieldValidator(),
|
||||
"org.signal.chat.require.range", new RangeFieldValidator(),
|
||||
"org.signal.chat.require.size", new SizeFieldValidator(),
|
||||
"org.signal.chat.require.base64url", new Base64UrlFieldValidator(),
|
||||
"org.signal.chat.require.identityType", new ServiceIdentifierIdentityTypeValidator()
|
||||
);
|
||||
private static final String REQUIRE_PATH = "org.signal.chat.require.";
|
||||
private static final String EACH_PATH = "org.signal.chat.require.each";
|
||||
|
||||
// The keys in this map correspond to the names of our custom FieldOptions as well as the names in the fields of
|
||||
// `ElementConstraint` which itself is the value of the `each` FieldOption. For this reason it's a good idea to make
|
||||
// the names match when they refer to the same validator.
|
||||
private final static Map<String, FieldValidator<?>> VALIDATORS = Map.of(
|
||||
"nonEmpty", new NonEmptyFieldValidator(),
|
||||
"specified", new EnumSpecifiedFieldValidator(),
|
||||
"e164", new E164FieldValidator(),
|
||||
"exactlySize", new ExactlySizeFieldValidator(),
|
||||
"range", new RangeFieldValidator(),
|
||||
"size", new SizeFieldValidator(),
|
||||
"base64url", new Base64UrlFieldValidator(),
|
||||
"identityType", new ServiceIdentifierIdentityTypeValidator(),
|
||||
"present", new PresentFieldValidator());
|
||||
|
||||
@Override
|
||||
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(
|
||||
@@ -67,13 +74,13 @@ public class ValidatingInterceptor implements ServerInterceptor {
|
||||
validateMessage(message);
|
||||
super.onMessage(message);
|
||||
} catch (RuntimeException runtimeException) {
|
||||
final StatusRuntimeException grpcException = switch (runtimeException) {
|
||||
case StatusRuntimeException e -> e;
|
||||
default -> {
|
||||
log.error("Failure applying request validation to message {}", call.getMethodDescriptor().getFullMethodName(), runtimeException);
|
||||
yield GrpcExceptions.unavailable("failure applying request validation");
|
||||
}
|
||||
};
|
||||
final StatusRuntimeException grpcException = runtimeException instanceof StatusRuntimeException sre
|
||||
? sre
|
||||
: GrpcExceptions.unavailable("failure applying request validation");
|
||||
if (grpcException.getStatus().getCode() != Status.Code.INVALID_ARGUMENT) {
|
||||
log.error("Failure applying request validation to message {}",
|
||||
call.getMethodDescriptor().getFullMethodName(), runtimeException);
|
||||
}
|
||||
call.close(grpcException.getStatus(), grpcException.getTrailers());
|
||||
forwardCalls = false;
|
||||
}
|
||||
@@ -89,45 +96,95 @@ public class ValidatingInterceptor implements ServerInterceptor {
|
||||
}
|
||||
|
||||
private void validateMessage(final Object message) {
|
||||
if (message instanceof Message msg) {
|
||||
for (final Descriptors.FieldDescriptor fd : msg.getDescriptorForType().getFields()) {
|
||||
for (final Map.Entry<Descriptors.FieldDescriptor, Object> entry : fd.getOptions().getAllFields().entrySet()) {
|
||||
final Descriptors.FieldDescriptor extensionFieldDescriptor = entry.getKey();
|
||||
final String extensionName = extensionFieldDescriptor.getFullName();
|
||||
if (!(message instanceof Message msg)) {
|
||||
return;
|
||||
}
|
||||
for (final Descriptors.FieldDescriptor fd : msg.getDescriptorForType().getFields()) {
|
||||
for (final Map.Entry<Descriptors.FieldDescriptor, Object> entry : fd.getOptions().getAllFields().entrySet()) {
|
||||
final Descriptors.FieldDescriptor extensionFieldDescriptor = entry.getKey();
|
||||
|
||||
// If this is a oneof, but this field isn't set, we shouldn't validate it. We assume if you have a validator
|
||||
// that requires presence, you don't actually want presence enforcement on a oneof case.
|
||||
if (fd.getRealContainingOneof() != null && !msg.hasField(fd)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// first validate the field
|
||||
final FieldValidator validator = fieldValidators.get(extensionName);
|
||||
// not all extensions are validators, so `validator` value here could legitimately be `null`
|
||||
if (validator != null) {
|
||||
try {
|
||||
validator.validate(entry.getValue(), fd, msg);
|
||||
} catch (FieldValidationException e) {
|
||||
throw GrpcExceptions.fieldViolation(fd.getName(),
|
||||
"extension %s: %s".formatted(extensionName, e.getMessage()));
|
||||
}
|
||||
if (!extensionFieldDescriptor.getFullName().startsWith(REQUIRE_PATH) || (fd.getRealContainingOneof() != null && !msg.hasField(fd))) {
|
||||
// Either this is a non-require extension, or this is oneof but this field isn't set. In the latter case
|
||||
// we assume if you have a validator that requires presence, you don't actually want presence enforcement on
|
||||
// a oneof. In either case we should just skip this validator.
|
||||
} else if (extensionFieldDescriptor.getFullName().equals(EACH_PATH)) {
|
||||
if (!(entry.getValue() instanceof ElementConstraint elementConstraint)) {
|
||||
throw new IllegalStateException("'each' value must be an ElementConstraint");
|
||||
}
|
||||
validateRepeatedElementConstraints(elementConstraint, msg, fd);
|
||||
} else {
|
||||
validateField(getValidatorOrThrow(extensionFieldDescriptor), entry.getValue(), msg, fd);
|
||||
}
|
||||
}
|
||||
|
||||
// Recursively validate the field's value(s) if it is a message or a repeated field
|
||||
// gRPC's proto deserialization limits nesting to 100 so this has bounded stack usage
|
||||
if (fd.isRepeated() && msg.getField(fd) instanceof List list) {
|
||||
// Checking for repeated fields also handles maps, because maps are syntax sugar for repeated MapEntries
|
||||
// which themselves are Messages that will be recursively descended.
|
||||
for (final Object o : list) {
|
||||
validateMessage(o);
|
||||
}
|
||||
} else if (fd.hasPresence() && msg.hasField(fd)) {
|
||||
// If the field has presence information and is present, recursively validate it. Not all fields have
|
||||
// presence, but we only validate Message type fields anyway, which always have explicit presence.
|
||||
validateMessage(msg.getField(fd));
|
||||
// Recursively validate the field's value(s) if it is a message or a repeated field
|
||||
// gRPC's proto deserialization limits nesting to 100 so this has bounded stack usage
|
||||
if (fd.isRepeated() && msg.getField(fd) instanceof List list) {
|
||||
// Checking for repeated fields also handles maps, because maps are syntax sugar for repeated MapEntries
|
||||
// which themselves are Messages that will be recursively descended.
|
||||
for (final Object o : list) {
|
||||
validateMessage(o);
|
||||
}
|
||||
} else if (fd.hasPresence() && msg.hasField(fd)) {
|
||||
// If the field has presence information and is present, recursively validate it. Not all fields have
|
||||
// presence, but we only validate Message type fields anyway, which always have explicit presence.
|
||||
validateMessage(msg.getField(fd));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void validateField(final FieldValidator<?> validator, final Object extensionValue, final Message msg, final Descriptors.FieldDescriptor fd) {
|
||||
// for the fields with an `optional` modifier, checking if the field was set
|
||||
// and if not, checking if extension allows missing optional field
|
||||
if (fd.hasPresence() && !msg.hasField(fd)) {
|
||||
switch (validator.getMissingOptionalAction()) {
|
||||
case FAIL -> throw fieldViolation(fd, validator.getExtensionName(), "extension requires a value to be set");
|
||||
case SUCCEED -> {
|
||||
return;
|
||||
}
|
||||
case VALIDATE_DEFAULT_VALUE -> {}
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
validator.validate(extensionValue, fd, msg.getField(fd));
|
||||
} catch (FieldValidationException e) {
|
||||
throw fieldViolation(fd, validator.getExtensionName(), e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private void validateRepeatedElementConstraints(
|
||||
final ElementConstraint elementConstraint,
|
||||
final Message message,
|
||||
final Descriptors.FieldDescriptor fd) {
|
||||
if (!fd.isRepeated() || fd.isMapField()) {
|
||||
throw new IllegalStateException("each may only be applied to repeated fields");
|
||||
}
|
||||
|
||||
for (final Map.Entry<Descriptors.FieldDescriptor, Object> entry : elementConstraint.getAllFields().entrySet()) {
|
||||
final FieldValidator<?> elementValidator = getValidatorOrThrow(entry.getKey());
|
||||
final int count = message.getRepeatedFieldCount(fd);
|
||||
for (int i = 0; i < count; i++) {
|
||||
final Object element = message.getRepeatedField(fd, i);
|
||||
try {
|
||||
elementValidator.validate(entry.getValue(), fd, element);
|
||||
} catch (final FieldValidationException e) {
|
||||
throw fieldViolation(fd, entry.getKey().getFullName(), "element [%d]: %s".formatted(i, e.getMessage()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private StatusRuntimeException fieldViolation(final Descriptors.FieldDescriptor fd, final String extensionName, final String message) {
|
||||
return GrpcExceptions.fieldViolation(fd.getName(), "extension %s: %s".formatted(extensionName, message));
|
||||
}
|
||||
|
||||
private static FieldValidator<?> getValidatorOrThrow(final Descriptors.FieldDescriptor extensionFd) {
|
||||
final FieldValidator<?> validator = VALIDATORS.get(extensionFd.getName());
|
||||
if (validator == null) {
|
||||
throw new IllegalStateException("unrecognized extension " + extensionFd.getFullName());
|
||||
}
|
||||
return validator;
|
||||
}
|
||||
|
||||
}
|
||||
+38
-9
@@ -8,10 +8,9 @@ import com.google.common.annotations.VisibleForTesting;
|
||||
import io.dropwizard.lifecycle.Managed;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.netty.bootstrap.ServerBootstrap;
|
||||
import io.netty.buffer.ByteBufAllocator;
|
||||
import io.netty.buffer.ByteBufAllocatorMetricProvider;
|
||||
import io.netty.channel.Channel;
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import io.netty.channel.ChannelInboundHandlerAdapter;
|
||||
import io.netty.channel.ChannelInitializer;
|
||||
import io.netty.channel.ChannelOption;
|
||||
import io.netty.channel.ChannelPipeline;
|
||||
@@ -34,15 +33,19 @@ import io.netty.handler.timeout.IdleStateEvent;
|
||||
import io.netty.handler.timeout.IdleStateHandler;
|
||||
import io.netty.util.Mapping;
|
||||
import java.io.IOException;
|
||||
import java.math.BigDecimal;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.SocketAddress;
|
||||
import java.net.SocketException;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.Supplier;
|
||||
import javax.annotation.Nullable;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicOmnibusConfiguration;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
|
||||
/// An HTTP/2 server that proxies H2 streams to configurable backends via path-based routing
|
||||
@@ -55,10 +58,12 @@ public class OmnibusH2Server implements Managed {
|
||||
new OmnibusExceptionHandler("omnibus-handshake", List.of(SocketException.class, DecoderException.class, IOException.class));
|
||||
private static final OmnibusExceptionHandler SESSION_EXCEPTION_HANDLER =
|
||||
new OmnibusExceptionHandler("omnibus-session", List.of(Http2Exception.class));
|
||||
private static final OmnibusLoadShedHandler LOAD_SHED_HANDLER = new OmnibusLoadShedHandler();
|
||||
private static final String IDLE_DISCONNECT_COUNTER_NAME = MetricsUtil.name(OmnibusH2Server.class, "idleDisconnect");
|
||||
|
||||
private final @Nullable Mapping<String, SslContext> sslContextBySni;
|
||||
private final OmnibusRouter router;
|
||||
private final Supplier<DynamicOmnibusConfiguration> configurationSupplier;
|
||||
private final Duration idleTimeout;
|
||||
private final DefaultEventLoopGroup localEventLoopGroup;
|
||||
private final NioEventLoopGroup nioEventLoopGroup;
|
||||
@@ -68,20 +73,24 @@ public class OmnibusH2Server implements Managed {
|
||||
|
||||
/// Create an omnibus server
|
||||
///
|
||||
/// @param sslContextBySni If not null, a mapping between domain (SNI) and the appropriate SslContext to use for
|
||||
/// that SNI. If null, the server will not include TLS (h2c with prior-knowledge)
|
||||
/// @param nioEventLoopGroup Event loop to use for all NIO channel pipelines
|
||||
/// @param localEventLoopGroup Event loop to use for all local channel pipelines
|
||||
/// @param bindAddress The address the server should listen on
|
||||
/// @param router How the server should select backends based on request paths
|
||||
/// @param sslContextBySni If not null, a mapping between domain (SNI) and the appropriate SslContext to use for
|
||||
/// that SNI. If null, the server will not include TLS (h2c with prior-knowledge)
|
||||
/// @param nioEventLoopGroup Event loop to use for all NIO channel pipelines
|
||||
/// @param localEventLoopGroup Event loop to use for all local channel pipelines
|
||||
/// @param bindAddress The address the server should listen on
|
||||
/// @param router How the server should select backends based on request paths
|
||||
/// @param configurationSupplier Dynamic configuration supplier
|
||||
/// @param idleTimeout How long to wait before terminating idle TCP connections
|
||||
public OmnibusH2Server(
|
||||
final @Nullable Mapping<String, SslContext> sslContextBySni,
|
||||
final NioEventLoopGroup nioEventLoopGroup,
|
||||
final DefaultEventLoopGroup localEventLoopGroup,
|
||||
final SocketAddress bindAddress,
|
||||
final OmnibusRouter router,
|
||||
final Supplier<DynamicOmnibusConfiguration> configurationSupplier,
|
||||
final Duration idleTimeout) {
|
||||
this.sslContextBySni = sslContextBySni;
|
||||
this.configurationSupplier = configurationSupplier;
|
||||
this.nioEventLoopGroup = nioEventLoopGroup;
|
||||
this.localEventLoopGroup = localEventLoopGroup;
|
||||
this.bindAddress = bindAddress;
|
||||
@@ -114,7 +123,15 @@ public class OmnibusH2Server implements Managed {
|
||||
ch.pipeline().addLast(new ProxyProtocolHandler());
|
||||
ch.pipeline().addLast(new ProxyMessageAttributeSetterHandler());
|
||||
if (sslContextBySni == null) {
|
||||
configureH2Pipeline(ch.pipeline());
|
||||
// Defer setting up the H2 pipeline until the channel is active, so we know we can immediately write
|
||||
// to it if we need to.
|
||||
ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
|
||||
@Override
|
||||
public void channelActive(final ChannelHandlerContext ctx) {
|
||||
configureH2Pipeline(ctx.pipeline());
|
||||
ctx.pipeline().remove(this);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
ch.pipeline().addLast(new SniHandler(sslContextBySni));
|
||||
ch.pipeline().addLast(new ApplicationProtocolNegotiationHandler(ApplicationProtocolNames.HTTP_2) {
|
||||
@@ -156,6 +173,11 @@ public class OmnibusH2Server implements Managed {
|
||||
// Advertise support for RFC-8441 extended connect
|
||||
final Http2Settings settings = Http2Settings.defaultSettings().connectProtocolEnabled(true);
|
||||
pipeline.addLast(Http2FrameCodecBuilder.forServer().initialSettings(settings).build());
|
||||
if (shouldRejectConnection()) {
|
||||
pipeline.addLast(LOAD_SHED_HANDLER);
|
||||
return;
|
||||
}
|
||||
|
||||
pipeline.addLast(new Http2MultiplexHandler(new ChannelInitializer<Http2StreamChannel>() {
|
||||
@Override
|
||||
protected void initChannel(final Http2StreamChannel ch) {
|
||||
@@ -164,4 +186,11 @@ public class OmnibusH2Server implements Managed {
|
||||
}));
|
||||
pipeline.addLast(SESSION_EXCEPTION_HANDLER);
|
||||
}
|
||||
|
||||
private boolean shouldRejectConnection() {
|
||||
final DynamicOmnibusConfiguration configuration = configurationSupplier.get();
|
||||
final BigDecimal rejectionRatio = configuration.rejectConnectionRatio();
|
||||
return rejectionRatio.compareTo(BigDecimal.ZERO) > 0 &&
|
||||
ThreadLocalRandom.current().nextDouble() < rejectionRatio.doubleValue();
|
||||
}
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.grpc.net;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.netty.channel.ChannelFutureListener;
|
||||
import io.netty.channel.ChannelHandler;
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import io.netty.channel.ChannelInboundHandlerAdapter;
|
||||
import io.netty.handler.codec.http2.DefaultHttp2GoAwayFrame;
|
||||
import io.netty.util.ReferenceCountUtil;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
|
||||
@ChannelHandler.Sharable
|
||||
public class OmnibusLoadShedHandler extends ChannelInboundHandlerAdapter {
|
||||
// Error code to put in GOAWAY frames that indicate load-shedding. 0x40
|
||||
// is an arbitrary non-reserved code per https://datatracker.ietf.org/doc/html/rfc7540#section-7
|
||||
@VisibleForTesting
|
||||
static final int LOAD_SHED_ERROR_CODE = 0x40;
|
||||
|
||||
private static final Counter LOAD_SHED_COUNTER =
|
||||
Metrics.counter(MetricsUtil.name(OmnibusLoadShedHandler.class, "loadShed"));
|
||||
|
||||
@Override
|
||||
public void handlerAdded(final ChannelHandlerContext ctx) {
|
||||
LOAD_SHED_COUNTER.increment();
|
||||
final DefaultHttp2GoAwayFrame goAwayFrame = new DefaultHttp2GoAwayFrame(LOAD_SHED_ERROR_CODE);
|
||||
ctx.writeAndFlush(goAwayFrame).addListener(ChannelFutureListener.CLOSE);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void channelRead(ChannelHandlerContext ctx, Object msg) {
|
||||
// Drop any attempts to open streams
|
||||
ReferenceCountUtil.release(msg);
|
||||
}
|
||||
|
||||
}
|
||||
+1
-5
@@ -6,16 +6,12 @@
|
||||
package org.whispersystems.textsecuregcm.grpc.validators;
|
||||
|
||||
import com.google.protobuf.Descriptors;
|
||||
import org.whispersystems.textsecuregcm.util.ImpossiblePhoneNumberException;
|
||||
import org.whispersystems.textsecuregcm.util.NonNormalizedPhoneNumberException;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
import java.util.Base64;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
|
||||
/// Validate that a string field is a valid base64 url string (padded or unpadded)
|
||||
public class Base64UrlFieldValidator extends BaseFieldValidator<Boolean> {
|
||||
public class Base64UrlFieldValidator extends FieldValidator<Boolean> {
|
||||
|
||||
public Base64UrlFieldValidator() {
|
||||
super("base64url", Set.of(Descriptors.FieldDescriptor.Type.STRING), MissingOptionalAction.SUCCEED, false);
|
||||
|
||||
-143
@@ -1,143 +0,0 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.grpc.validators;
|
||||
|
||||
import static java.util.Objects.requireNonNull;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import com.google.protobuf.Descriptors;
|
||||
import com.google.protobuf.Message;
|
||||
import java.util.Set;
|
||||
|
||||
public abstract class BaseFieldValidator<T> implements FieldValidator {
|
||||
|
||||
private final String extensionName;
|
||||
|
||||
private final Set<Descriptors.FieldDescriptor.Type> supportedTypes;
|
||||
|
||||
private final MissingOptionalAction missingOptionalAction;
|
||||
|
||||
private final boolean applicableToRepeated;
|
||||
|
||||
protected enum MissingOptionalAction {
|
||||
FAIL,
|
||||
SUCCEED,
|
||||
VALIDATE_DEFAULT_VALUE
|
||||
}
|
||||
|
||||
|
||||
protected BaseFieldValidator(
|
||||
final String extensionName,
|
||||
final Set<Descriptors.FieldDescriptor.Type> supportedTypes,
|
||||
final MissingOptionalAction missingOptionalAction,
|
||||
final boolean applicableToRepeated) {
|
||||
this.extensionName = requireNonNull(extensionName);
|
||||
this.supportedTypes = requireNonNull(supportedTypes);
|
||||
this.missingOptionalAction = missingOptionalAction;
|
||||
this.applicableToRepeated = applicableToRepeated;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void validate(
|
||||
final Object extensionValue,
|
||||
final Descriptors.FieldDescriptor fd,
|
||||
final Message msg) throws FieldValidationException {
|
||||
final T extensionValueTyped = resolveExtensionValue(extensionValue);
|
||||
|
||||
// for the fields with an `optional` modifier, checking if the field was set
|
||||
// and if not, checking if extension allows missing optional field
|
||||
if (fd.hasPresence() && !msg.hasField(fd)) {
|
||||
switch (missingOptionalAction) {
|
||||
case FAIL -> {
|
||||
throw new FieldValidationException("extension requires a value to be set");
|
||||
}
|
||||
case SUCCEED -> {
|
||||
return;
|
||||
}
|
||||
case VALIDATE_DEFAULT_VALUE -> {
|
||||
// just continuing
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// for the `repeated` fields, checking if it's supported by the extension
|
||||
if (fd.isRepeated()) {
|
||||
if (applicableToRepeated) {
|
||||
validateRepeatedField(extensionValueTyped, fd, msg);
|
||||
return;
|
||||
}
|
||||
throw new IllegalArgumentException("can't apply extension %s to `repeated` field %s"
|
||||
.formatted(extensionName, fd.getFullName()));
|
||||
}
|
||||
|
||||
// checking field type against the set of supported types
|
||||
final Descriptors.FieldDescriptor.Type type = fd.getType();
|
||||
if (!supportedTypes.contains(type)) {
|
||||
throw new IllegalArgumentException("can't apply extension %s to field %s of type %s".formatted(
|
||||
extensionName, fd.getFullName(), type));
|
||||
}
|
||||
switch (type) {
|
||||
case INT64, UINT64, INT32, FIXED64, FIXED32, UINT32, SFIXED32, SFIXED64, SINT32, SINT64 ->
|
||||
validateIntegerNumber(extensionValueTyped, ((Number) msg.getField(fd)).longValue(), type);
|
||||
case STRING -> validateStringValue(extensionValueTyped, (String) msg.getField(fd));
|
||||
case BYTES -> validateBytesValue(extensionValueTyped, (ByteString) msg.getField(fd));
|
||||
case ENUM -> validateEnumValue(extensionValueTyped, (Descriptors.EnumValueDescriptor) msg.getField(fd));
|
||||
case MESSAGE -> {
|
||||
validateMessageValue(extensionValueTyped, (Message) msg.getField(fd));
|
||||
}
|
||||
case FLOAT, DOUBLE, BOOL, GROUP -> {
|
||||
// at this moment, there are no validations specific to these types of fields
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
protected abstract T resolveExtensionValue(final Object extensionValue) throws FieldValidationException;
|
||||
|
||||
protected void validateRepeatedField(
|
||||
final T extensionValue,
|
||||
final Descriptors.FieldDescriptor fd,
|
||||
final Message msg) throws FieldValidationException {
|
||||
throw new UnsupportedOperationException("`validateRepeatedField` method needs to be implemented");
|
||||
}
|
||||
|
||||
protected void validateIntegerNumber(
|
||||
final T extensionValue,
|
||||
final long fieldValue, final Descriptors.FieldDescriptor.Type type) throws FieldValidationException {
|
||||
throw new UnsupportedOperationException("`validateIntegerNumber` method needs to be implemented");
|
||||
}
|
||||
|
||||
protected void validateStringValue(
|
||||
final T extensionValue,
|
||||
final String fieldValue) throws FieldValidationException {
|
||||
throw new UnsupportedOperationException("`validateStringValue` method needs to be implemented");
|
||||
}
|
||||
|
||||
protected void validateBytesValue(
|
||||
final T extensionValue,
|
||||
final ByteString fieldValue) throws FieldValidationException {
|
||||
throw new UnsupportedOperationException("`validateBytesValue` method needs to be implemented");
|
||||
}
|
||||
|
||||
protected void validateEnumValue(
|
||||
final T extensionValue,
|
||||
final Descriptors.EnumValueDescriptor enumValueDescriptor) throws FieldValidationException {
|
||||
throw new UnsupportedOperationException("`validateEnumValue` method needs to be implemented");
|
||||
}
|
||||
|
||||
protected void validateMessageValue(
|
||||
final T extensionValue,
|
||||
final Message message) throws FieldValidationException {
|
||||
throw new UnsupportedOperationException("`validateMessageValue` method needs to be implemented");
|
||||
}
|
||||
|
||||
protected static boolean requireFlagExtension(final Object extensionValue) throws FieldValidationException {
|
||||
if (extensionValue instanceof Boolean flagIsOn && flagIsOn) {
|
||||
return true;
|
||||
}
|
||||
throw new UnsupportedOperationException("only value `true` is allowed");
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -11,7 +11,7 @@ import org.whispersystems.textsecuregcm.util.ImpossiblePhoneNumberException;
|
||||
import org.whispersystems.textsecuregcm.util.NonNormalizedPhoneNumberException;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
public class E164FieldValidator extends BaseFieldValidator<Boolean> {
|
||||
public class E164FieldValidator extends FieldValidator<Boolean> {
|
||||
|
||||
public E164FieldValidator() {
|
||||
super("e164", Set.of(Descriptors.FieldDescriptor.Type.STRING), MissingOptionalAction.SUCCEED, false);
|
||||
|
||||
+1
-1
@@ -8,7 +8,7 @@ package org.whispersystems.textsecuregcm.grpc.validators;
|
||||
import com.google.protobuf.Descriptors;
|
||||
import java.util.Set;
|
||||
|
||||
public class EnumSpecifiedFieldValidator extends BaseFieldValidator<Boolean> {
|
||||
public class EnumSpecifiedFieldValidator extends FieldValidator<Boolean> {
|
||||
|
||||
public EnumSpecifiedFieldValidator() {
|
||||
super("specified", Set.of(Descriptors.FieldDescriptor.Type.ENUM), MissingOptionalAction.FAIL, false);
|
||||
|
||||
+4
-6
@@ -7,11 +7,10 @@ package org.whispersystems.textsecuregcm.grpc.validators;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import com.google.protobuf.Descriptors;
|
||||
import com.google.protobuf.Message;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
public class ExactlySizeFieldValidator extends BaseFieldValidator<Set<Integer>> {
|
||||
public class ExactlySizeFieldValidator extends FieldValidator<Set<Integer>> {
|
||||
|
||||
public ExactlySizeFieldValidator() {
|
||||
super("exactlySize", Set.of(
|
||||
@@ -50,11 +49,10 @@ public class ExactlySizeFieldValidator extends BaseFieldValidator<Set<Integer>>
|
||||
protected void validateRepeatedField(
|
||||
final Set<Integer> permittedSizes,
|
||||
final Descriptors.FieldDescriptor fd,
|
||||
final Message msg) throws FieldValidationException {
|
||||
final int size = msg.getRepeatedFieldCount(fd);
|
||||
if (permittedSizes.contains(size)) {
|
||||
final List<?> repeated) throws FieldValidationException {
|
||||
if (permittedSizes.contains(repeated.size())) {
|
||||
return;
|
||||
}
|
||||
throw new FieldValidationException("list size is [%d] but expected to be one of %s".formatted(size, permittedSizes));
|
||||
throw new FieldValidationException("list size is [%d] but expected to be one of %s".formatted(repeated.size(), permittedSizes));
|
||||
}
|
||||
}
|
||||
+126
-3
@@ -5,11 +5,134 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.grpc.validators;
|
||||
|
||||
import static java.util.Objects.requireNonNull;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import com.google.protobuf.Descriptors;
|
||||
import com.google.protobuf.Message;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
public interface FieldValidator {
|
||||
public abstract class FieldValidator<T> {
|
||||
|
||||
void validate(Object extensionValue, Descriptors.FieldDescriptor fd, Message msg)
|
||||
throws FieldValidationException;
|
||||
private final String extensionName;
|
||||
|
||||
private final Set<Descriptors.FieldDescriptor.Type> supportedTypes;
|
||||
|
||||
private final MissingOptionalAction missingOptionalAction;
|
||||
|
||||
private final boolean applicableToRepeated;
|
||||
|
||||
public enum MissingOptionalAction {
|
||||
FAIL,
|
||||
SUCCEED,
|
||||
VALIDATE_DEFAULT_VALUE
|
||||
}
|
||||
|
||||
|
||||
protected FieldValidator(
|
||||
final String extensionName,
|
||||
final Set<Descriptors.FieldDescriptor.Type> supportedTypes,
|
||||
final MissingOptionalAction missingOptionalAction,
|
||||
final boolean applicableToRepeated) {
|
||||
this.extensionName = requireNonNull(extensionName);
|
||||
this.supportedTypes = requireNonNull(supportedTypes);
|
||||
this.missingOptionalAction = missingOptionalAction;
|
||||
this.applicableToRepeated = applicableToRepeated;
|
||||
}
|
||||
|
||||
public MissingOptionalAction getMissingOptionalAction() {
|
||||
return missingOptionalAction;
|
||||
}
|
||||
|
||||
public String getExtensionName() {
|
||||
return extensionName;
|
||||
}
|
||||
|
||||
|
||||
/// Validate a field
|
||||
///
|
||||
/// @param extensionValue The value of the option this field was annotated with
|
||||
/// @param fd The descriptor of the field to validate
|
||||
/// @param fieldValue The value of the field to validate
|
||||
/// @throws FieldValidationException if a field constraint was violated
|
||||
public final void validate(
|
||||
final Object extensionValue,
|
||||
final Descriptors.FieldDescriptor fd,
|
||||
final Object fieldValue) throws FieldValidationException {
|
||||
final T extensionValueTyped = resolveExtensionValue(extensionValue);
|
||||
|
||||
// for the `repeated` fields, checking if it's supported by the extension
|
||||
if (fd.isRepeated() && fieldValue instanceof List list) {
|
||||
if (!applicableToRepeated) {
|
||||
throw new IllegalArgumentException("can't apply extension %s to `repeated` field %s"
|
||||
.formatted(extensionName, fd.getFullName()));
|
||||
}
|
||||
validateRepeatedField(extensionValueTyped, fd, list);
|
||||
return;
|
||||
}
|
||||
final Descriptors.FieldDescriptor.Type type = fd.getType();
|
||||
if (!supportedTypes.contains(type)) {
|
||||
throw new IllegalArgumentException("can't apply extension %s to field %s of type %s".formatted(
|
||||
extensionName, fd.getFullName(), type));
|
||||
}
|
||||
switch (type) {
|
||||
case INT64, UINT64, INT32, FIXED64, FIXED32, UINT32, SFIXED32, SFIXED64, SINT32, SINT64 ->
|
||||
validateIntegerNumber(extensionValueTyped, ((Number) fieldValue).longValue(), type);
|
||||
case STRING -> validateStringValue(extensionValueTyped, (String) fieldValue);
|
||||
case BYTES -> validateBytesValue(extensionValueTyped, (ByteString) fieldValue);
|
||||
case ENUM -> validateEnumValue(extensionValueTyped, (Descriptors.EnumValueDescriptor) fieldValue);
|
||||
case MESSAGE -> validateMessageValue(extensionValueTyped, (Message) fieldValue);
|
||||
case FLOAT, DOUBLE, BOOL, GROUP -> {
|
||||
// at this moment, there are no validations specific to these types of fields
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
protected abstract T resolveExtensionValue(final Object extensionValue) throws FieldValidationException;
|
||||
|
||||
protected void validateRepeatedField(
|
||||
final T extensionValue,
|
||||
final Descriptors.FieldDescriptor fd,
|
||||
final List<?> repeated) throws FieldValidationException {
|
||||
throw new UnsupportedOperationException("`validateRepeatedField` method needs to be implemented");
|
||||
}
|
||||
|
||||
protected void validateIntegerNumber(
|
||||
final T extensionValue,
|
||||
final long fieldValue, final Descriptors.FieldDescriptor.Type type) throws FieldValidationException {
|
||||
throw new UnsupportedOperationException("`validateIntegerNumber` method needs to be implemented");
|
||||
}
|
||||
|
||||
protected void validateStringValue(
|
||||
final T extensionValue,
|
||||
final String fieldValue) throws FieldValidationException {
|
||||
throw new UnsupportedOperationException("`validateStringValue` method needs to be implemented");
|
||||
}
|
||||
|
||||
protected void validateBytesValue(
|
||||
final T extensionValue,
|
||||
final ByteString fieldValue) throws FieldValidationException {
|
||||
throw new UnsupportedOperationException("`validateBytesValue` method needs to be implemented");
|
||||
}
|
||||
|
||||
protected void validateEnumValue(
|
||||
final T extensionValue,
|
||||
final Descriptors.EnumValueDescriptor enumValueDescriptor) throws FieldValidationException {
|
||||
throw new UnsupportedOperationException("`validateEnumValue` method needs to be implemented");
|
||||
}
|
||||
|
||||
protected void validateMessageValue(
|
||||
final T extensionValue,
|
||||
final Message message) throws FieldValidationException {
|
||||
throw new UnsupportedOperationException("`validateMessageValue` method needs to be implemented");
|
||||
}
|
||||
|
||||
protected static boolean requireFlagExtension(final Object extensionValue) throws FieldValidationException {
|
||||
if (extensionValue instanceof Boolean flagIsOn && flagIsOn) {
|
||||
return true;
|
||||
}
|
||||
throw new UnsupportedOperationException("only value `true` is allowed");
|
||||
}
|
||||
}
|
||||
+4
-4
@@ -7,11 +7,11 @@ package org.whispersystems.textsecuregcm.grpc.validators;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import com.google.protobuf.Descriptors;
|
||||
import com.google.protobuf.Message;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
public class NonEmptyFieldValidator extends BaseFieldValidator<Boolean> {
|
||||
public class NonEmptyFieldValidator extends FieldValidator<Boolean> {
|
||||
|
||||
public NonEmptyFieldValidator() {
|
||||
super("nonEmpty", Set.of(
|
||||
@@ -49,8 +49,8 @@ public class NonEmptyFieldValidator extends BaseFieldValidator<Boolean> {
|
||||
protected void validateRepeatedField(
|
||||
final Boolean extensionValue,
|
||||
final Descriptors.FieldDescriptor fd,
|
||||
final Message msg) throws FieldValidationException {
|
||||
if (msg.getRepeatedFieldCount(fd) > 0) {
|
||||
final List<?> repeated) throws FieldValidationException {
|
||||
if (repeated.size() > 0) {
|
||||
return;
|
||||
}
|
||||
throw new FieldValidationException("repeated field is expected to be non-empty");
|
||||
|
||||
+1
-1
@@ -9,7 +9,7 @@ import com.google.protobuf.Descriptors;
|
||||
import com.google.protobuf.Message;
|
||||
import java.util.Set;
|
||||
|
||||
public class PresentFieldValidator extends BaseFieldValidator<Boolean> {
|
||||
public class PresentFieldValidator extends FieldValidator<Boolean> {
|
||||
|
||||
public PresentFieldValidator() {
|
||||
super("present",
|
||||
|
||||
+1
-1
@@ -9,7 +9,7 @@ import com.google.protobuf.Descriptors;
|
||||
import java.util.Set;
|
||||
import org.signal.chat.require.ValueRangeConstraint;
|
||||
|
||||
public class RangeFieldValidator extends BaseFieldValidator<Range> {
|
||||
public class RangeFieldValidator extends FieldValidator<Range> {
|
||||
|
||||
private static final Set<Descriptors.FieldDescriptor.Type> UNSIGNED_TYPES = Set.of(
|
||||
Descriptors.FieldDescriptor.Type.FIXED32,
|
||||
|
||||
+1
-1
@@ -12,7 +12,7 @@ import java.util.Set;
|
||||
import org.signal.chat.common.IdentityType;
|
||||
import org.signal.chat.common.ServiceIdentifier;
|
||||
|
||||
public class ServiceIdentifierIdentityTypeValidator extends BaseFieldValidator<IdentityType> {
|
||||
public class ServiceIdentifierIdentityTypeValidator extends FieldValidator<IdentityType> {
|
||||
|
||||
public ServiceIdentifierIdentityTypeValidator() {
|
||||
super("identityType", Set.of(Descriptors.FieldDescriptor.Type.MESSAGE), MissingOptionalAction.SUCCEED, false);
|
||||
|
||||
+4
-4
@@ -7,11 +7,11 @@ package org.whispersystems.textsecuregcm.grpc.validators;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import com.google.protobuf.Descriptors;
|
||||
import com.google.protobuf.Message;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import org.signal.chat.require.SizeConstraint;
|
||||
|
||||
public class SizeFieldValidator extends BaseFieldValidator<Range> {
|
||||
public class SizeFieldValidator extends FieldValidator<Range> {
|
||||
|
||||
public SizeFieldValidator() {
|
||||
super("size", Set.of(
|
||||
@@ -45,8 +45,8 @@ public class SizeFieldValidator extends BaseFieldValidator<Range> {
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void validateRepeatedField(final Range range, final Descriptors.FieldDescriptor fd, final Message msg) throws FieldValidationException {
|
||||
final int size = msg.getRepeatedFieldCount(fd);
|
||||
protected void validateRepeatedField(final Range range, final Descriptors.FieldDescriptor fd, final List<?> repeated) throws FieldValidationException {
|
||||
final int size = repeated.size();
|
||||
if (size < range.min() || size > range.max()) {
|
||||
throw new FieldValidationException("field value is [%d] but expected to be within the [%d, %d] range".formatted(
|
||||
size, range.min(), range.max()));
|
||||
|
||||
+9
-8
@@ -29,8 +29,10 @@ import org.signal.keytransparency.client.E164SearchRequest;
|
||||
import org.signal.keytransparency.client.KeyTransparencyQueryServiceGrpc;
|
||||
import org.signal.keytransparency.client.MonitorRequest;
|
||||
import org.signal.keytransparency.client.MonitorResponse;
|
||||
import org.signal.keytransparency.client.MonitorResponseV2;
|
||||
import org.signal.keytransparency.client.SearchRequest;
|
||||
import org.signal.keytransparency.client.SearchResponse;
|
||||
import org.signal.keytransparency.client.SearchResponseV2;
|
||||
import org.signal.keytransparency.client.UsernameHashMonitorRequest;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
@@ -110,7 +112,7 @@ public class KeyTransparencyServiceClient implements Managed {
|
||||
}
|
||||
|
||||
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
|
||||
public SearchResponse search(
|
||||
public SearchResponseV2 search(
|
||||
final ByteString aci,
|
||||
final ByteString aciIdentityKey,
|
||||
final Optional<ByteString> usernameHash,
|
||||
@@ -132,13 +134,13 @@ public class KeyTransparencyServiceClient implements Managed {
|
||||
return search(searchRequestBuilder.build());
|
||||
}
|
||||
|
||||
public SearchResponse search(final SearchRequest request) {
|
||||
public SearchResponseV2 search(final SearchRequest request) {
|
||||
return stub.withDeadline(toDeadline(KEY_TRANSPARENCY_RPC_TIMEOUT))
|
||||
.search(request);
|
||||
.searchV2(request);
|
||||
}
|
||||
|
||||
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
|
||||
public MonitorResponse monitor(final AciMonitorRequest aciMonitorRequest,
|
||||
public MonitorResponseV2 monitor(final AciMonitorRequest aciMonitorRequest,
|
||||
final Optional<UsernameHashMonitorRequest> usernameHashMonitorRequest,
|
||||
final Optional<E164MonitorRequest> e164MonitorRequest,
|
||||
final long lastTreeHeadSize,
|
||||
@@ -155,12 +157,11 @@ public class KeyTransparencyServiceClient implements Managed {
|
||||
return monitor(monitorRequestBuilder.build());
|
||||
}
|
||||
|
||||
public MonitorResponse monitor(final MonitorRequest request) {
|
||||
public MonitorResponseV2 monitor(final MonitorRequest request) {
|
||||
return stub.withDeadline(toDeadline(KEY_TRANSPARENCY_RPC_TIMEOUT))
|
||||
.monitor(request);
|
||||
.monitorV2(request);
|
||||
}
|
||||
|
||||
|
||||
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
|
||||
public DistinguishedResponse getDistinguishedKey(final Optional<Long> lastTreeHeadSize) {
|
||||
final DistinguishedRequest request = lastTreeHeadSize.map(
|
||||
@@ -171,7 +172,7 @@ public class KeyTransparencyServiceClient implements Managed {
|
||||
|
||||
public DistinguishedResponse distinguished(final DistinguishedRequest request) {
|
||||
return stub.withDeadline(toDeadline(KEY_TRANSPARENCY_RPC_TIMEOUT))
|
||||
.distinguished(request);
|
||||
.distinguishedV2(request);
|
||||
}
|
||||
|
||||
private static Deadline toDeadline(final Duration timeout) {
|
||||
|
||||
@@ -28,6 +28,7 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
|
||||
ALLOCATE_DEVICE("allocateDevice", new RateLimiterConfig(6, Duration.ofMinutes(2), false)),
|
||||
VERIFY_DEVICE("verifyDevice", new RateLimiterConfig(6, Duration.ofMinutes(2), false)),
|
||||
PROFILE("profile", new RateLimiterConfig(4320, Duration.ofSeconds(20), true)),
|
||||
PROFILE_AVATAR_BYTES("profileAvatarBytes", new RateLimiterConfig(DataSize.mebibytes(100).toBytes(), Duration.ofNanos(10000), true)),
|
||||
STICKER_PACK("stickerPack", new RateLimiterConfig(50, Duration.ofMinutes(72), false)),
|
||||
USERNAME_LOOKUP("usernameLookup", new RateLimiterConfig(100, Duration.ofMinutes(15), true)),
|
||||
USERNAME_SET("usernameSet", new RateLimiterConfig(100, Duration.ofMinutes(15), false)),
|
||||
@@ -61,6 +62,7 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
|
||||
DEVICE_CHECK_CHALLENGE("deviceCheckChallenge", new RateLimiterConfig(10, Duration.ofMinutes(1), false)),
|
||||
SUBMIT_CALL_QUALITY_SURVEY("submitCallQualitySurvey", new RateLimiterConfig(100, Duration.ofMinutes(1), true)),
|
||||
BATCH_IDENTITY_CHECK("batchIdentityCheck", new RateLimiterConfig(100, Duration.ofMinutes(1), true)),
|
||||
CREATE_DONATION_PERMIT("createDonationCredential", new RateLimiterConfig(30, Duration.ofHours(4), true)),
|
||||
ONE_TIME_DONATION("oneTimeDonation", new RateLimiterConfig(5, Duration.ofMinutes(1), true)),
|
||||
ADD_SUBSCRIPTION_PAYMENT_METHOD("addSubscriptionPaymentMethod", new RateLimiterConfig(10, Duration.ofMinutes(1), true)),
|
||||
;
|
||||
@@ -133,6 +135,10 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
|
||||
return forDescriptor(For.PROFILE);
|
||||
}
|
||||
|
||||
public RateLimiter getProfileAvatarBytesLimiter() {
|
||||
return forDescriptor(For.PROFILE_AVATAR_BYTES);
|
||||
}
|
||||
|
||||
public RateLimiter getStickerPackLimiter() {
|
||||
return forDescriptor(For.STICKER_PACK);
|
||||
}
|
||||
@@ -241,7 +247,7 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
|
||||
return forDescriptor(For.SUBMIT_CALL_QUALITY_SURVEY);
|
||||
}
|
||||
|
||||
public RateLimiter getBatchIdentityCheckLimiter() {
|
||||
return forDescriptor(For.BATCH_IDENTITY_CHECK);
|
||||
public RateLimiter getCreateDonationPermitLimiter() {
|
||||
return forDescriptor(For.CREATE_DONATION_PERMIT);
|
||||
}
|
||||
}
|
||||
@@ -35,6 +35,7 @@ public final class MessageMetrics {
|
||||
|
||||
public static String GRPC_CHANNEL = "grpc";
|
||||
public static String WEBSOCKET_CHANNEL = "websocket";
|
||||
public static String MESSAGELESS_WEBSOCKET_CHANNEL = "messageless-websocket";
|
||||
|
||||
@VisibleForTesting
|
||||
static final String MISMATCHED_ACCOUNT_ENVELOPE_UUID_COUNTER_NAME = name(MessageMetrics.class,
|
||||
|
||||
+15
@@ -16,6 +16,7 @@ import io.micrometer.core.instrument.Tags;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.atomic.LongAdder;
|
||||
import javax.annotation.Nullable;
|
||||
import org.glassfish.jersey.server.ContainerResponse;
|
||||
import org.glassfish.jersey.server.monitoring.RequestEvent;
|
||||
@@ -44,6 +45,8 @@ public class MetricsRequestEventListener implements RequestEventListener {
|
||||
public static final String RESPONSE_BYTES_COUNTER_NAME = name(MetricsRequestEventListener.class, "responseBytes");
|
||||
public static final String REQUEST_BYTES_COUNTER_NAME = name(MetricsRequestEventListener.class, "requestBytes");
|
||||
|
||||
private static final String ACTIVE_REQUESTS_GAUGE_NAME = name(MetricsRequestEventListener.class, "activeRequests");
|
||||
|
||||
@VisibleForTesting
|
||||
static final String PATH_TAG = "path";
|
||||
|
||||
@@ -65,6 +68,8 @@ public class MetricsRequestEventListener implements RequestEventListener {
|
||||
private final TrafficSource trafficSource;
|
||||
private final MeterRegistry meterRegistry;
|
||||
|
||||
private final LongAdder activeRequests;
|
||||
|
||||
public MetricsRequestEventListener(final TrafficSource trafficSource, final ClientReleaseManager clientReleaseManager) {
|
||||
this(trafficSource, Metrics.globalRegistry, clientReleaseManager);
|
||||
|
||||
@@ -81,10 +86,20 @@ public class MetricsRequestEventListener implements RequestEventListener {
|
||||
this.trafficSource = trafficSource;
|
||||
this.meterRegistry = meterRegistry;
|
||||
this.clientReleaseManager = clientReleaseManager;
|
||||
|
||||
this.activeRequests = meterRegistry.gauge(ACTIVE_REQUESTS_GAUGE_NAME, new LongAdder());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onEvent(final RequestEvent event) {
|
||||
if (event.getType() == RequestEvent.Type.RESOURCE_METHOD_START) {
|
||||
activeRequests.increment();
|
||||
}
|
||||
|
||||
if (event.getType() == RequestEvent.Type.RESOURCE_METHOD_FINISHED) {
|
||||
activeRequests.decrement();
|
||||
}
|
||||
|
||||
if (event.getType() == RequestEvent.Type.FINISHED) {
|
||||
if (!event.getUriInfo().getMatchedTemplates().isEmpty()) {
|
||||
@Nullable final UserAgent userAgent;
|
||||
|
||||
@@ -5,7 +5,6 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.metrics;
|
||||
|
||||
import com.codahale.metrics.SharedMetricRegistries;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.dropwizard.core.setup.Environment;
|
||||
import io.micrometer.core.instrument.Meter;
|
||||
@@ -36,7 +35,6 @@ import org.eclipse.jetty.util.component.LifeCycle;
|
||||
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.util.Constants;
|
||||
|
||||
public class MetricsUtil {
|
||||
|
||||
@@ -69,8 +67,6 @@ public class MetricsUtil {
|
||||
|
||||
registeredMetrics = true;
|
||||
|
||||
SharedMetricRegistries.add(Constants.METRICS_NAME, environment.metrics());
|
||||
|
||||
Duration shutdownWaitDuration = Duration.ZERO;
|
||||
|
||||
if (config.getOpenTelemetryConfiguration().enabled()) {
|
||||
|
||||
+105
-112
@@ -19,32 +19,31 @@ import java.security.NoSuchAlgorithmException;
|
||||
import java.time.Duration;
|
||||
import java.util.Base64;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import javax.annotation.Nullable;
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.signal.registration.rpc.CheckVerificationCodeRequest;
|
||||
import org.signal.registration.rpc.CheckVerificationCodeResponse;
|
||||
import org.signal.registration.rpc.CreateRegistrationSessionRequest;
|
||||
import org.signal.registration.rpc.CreateRegistrationSessionResponse;
|
||||
import org.signal.registration.rpc.GetRegistrationSessionMetadataRequest;
|
||||
import org.signal.registration.rpc.GetRegistrationSessionMetadataResponse;
|
||||
import org.signal.registration.rpc.RegistrationServiceGrpc;
|
||||
import org.signal.registration.rpc.RegistrationSessionMetadata;
|
||||
import org.signal.registration.rpc.SendVerificationCodeRequest;
|
||||
import org.signal.registration.rpc.SendVerificationCodeResponse;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.controllers.VerificationSessionRateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.entities.RegistrationServiceSession;
|
||||
import org.whispersystems.textsecuregcm.util.CompletableFutureUtil;
|
||||
|
||||
public class RegistrationServiceClient implements Managed {
|
||||
|
||||
private static final Base64.Encoder BASE64_UNPADDED_ENCODER = Base64.getEncoder().withoutPadding();
|
||||
|
||||
private final ManagedChannel channel;
|
||||
private final RegistrationServiceGrpc.RegistrationServiceFutureStub stub;
|
||||
private final Executor callbackExecutor;
|
||||
private final RegistrationServiceGrpc.RegistrationServiceBlockingStub stub;
|
||||
private final byte[] collationKeySalt;
|
||||
|
||||
/**
|
||||
@@ -68,8 +67,7 @@ public class RegistrationServiceClient implements Managed {
|
||||
final int port,
|
||||
final CallCredentials callCredentials,
|
||||
final String caCertificatePem,
|
||||
final byte[] collationKeySalt,
|
||||
final Executor callbackExecutor) throws IOException {
|
||||
final byte[] collationKeySalt) throws IOException {
|
||||
|
||||
try (final ByteArrayInputStream certificateInputStream = new ByteArrayInputStream(caCertificatePem.getBytes(StandardCharsets.UTF_8))) {
|
||||
final ChannelCredentials tlsChannelCredentials = TlsChannelCredentials.newBuilder()
|
||||
@@ -81,9 +79,8 @@ public class RegistrationServiceClient implements Managed {
|
||||
.build();
|
||||
}
|
||||
|
||||
this.stub = RegistrationServiceGrpc.newFutureStub(channel).withCallCredentials(callCredentials);
|
||||
this.stub = RegistrationServiceGrpc.newBlockingStub(channel).withCallCredentials(callCredentials);
|
||||
this.collationKeySalt = collationKeySalt;
|
||||
this.callbackExecutor = callbackExecutor;
|
||||
|
||||
// Fail fast: reject bad keys
|
||||
try {
|
||||
@@ -93,52 +90,54 @@ public class RegistrationServiceClient implements Managed {
|
||||
}
|
||||
}
|
||||
|
||||
public CompletableFuture<RegistrationServiceSession> createRegistrationSession(
|
||||
public RegistrationServiceSession createRegistrationSession(
|
||||
final Phonenumber.PhoneNumber phoneNumber,
|
||||
final String sourceHost,
|
||||
final boolean accountExistsWithPhoneNumber,
|
||||
@Nullable final String clientMcc,
|
||||
@Nullable final String clientMnc,
|
||||
final Duration timeout) {
|
||||
final Duration timeout) throws RateLimitExceededException {
|
||||
|
||||
final long e164 = Long.parseLong(
|
||||
PhoneNumberUtil.getInstance().format(phoneNumber, PhoneNumberUtil.PhoneNumberFormat.E164).substring(1));
|
||||
final String rateLimitCollationKey = hmac(sourceHost);
|
||||
|
||||
return CompletableFutureUtil.toCompletableFuture(stub.withDeadline(toDeadline(timeout))
|
||||
final CreateRegistrationSessionResponse response = stub.withDeadline(toDeadline(timeout))
|
||||
.createSession(CreateRegistrationSessionRequest.newBuilder()
|
||||
.setE164(e164)
|
||||
.setAccountExistsWithE164(accountExistsWithPhoneNumber)
|
||||
.setRateLimitCollationKey(rateLimitCollationKey)
|
||||
.setMcc(clientMcc != null ? clientMcc : "")
|
||||
.setMnc(clientMnc != null ? clientMnc : "")
|
||||
.build()), callbackExecutor)
|
||||
.thenApply(response -> switch (response.getResponseCase()) {
|
||||
case SESSION_METADATA -> buildSessionResponseFromMetadata(response.getSessionMetadata());
|
||||
.build());
|
||||
|
||||
case ERROR -> {
|
||||
switch (response.getError().getErrorType()) {
|
||||
case CREATE_REGISTRATION_SESSION_ERROR_TYPE_RATE_LIMITED -> throw new CompletionException(
|
||||
new RateLimitExceededException(response.getError().getMayRetry()
|
||||
? Duration.ofSeconds(response.getError().getRetryAfterSeconds())
|
||||
: null
|
||||
));
|
||||
case CREATE_REGISTRATION_SESSION_ERROR_TYPE_ILLEGAL_PHONE_NUMBER -> throw new IllegalArgumentException();
|
||||
default -> throw new RuntimeException(
|
||||
"Unrecognized error type from registration service: " + response.getError().getErrorType());
|
||||
}
|
||||
}
|
||||
return switch (response.getResponseCase()) {
|
||||
case SESSION_METADATA -> buildSessionResponseFromMetadata(response.getSessionMetadata());
|
||||
|
||||
case RESPONSE_NOT_SET -> throw new RuntimeException("No response from registration service");
|
||||
});
|
||||
case ERROR -> {
|
||||
switch (response.getError().getErrorType()) {
|
||||
case CREATE_REGISTRATION_SESSION_ERROR_TYPE_RATE_LIMITED ->
|
||||
throw new RateLimitExceededException(response.getError().getMayRetry()
|
||||
? Duration.ofSeconds(response.getError().getRetryAfterSeconds())
|
||||
: null
|
||||
);
|
||||
case CREATE_REGISTRATION_SESSION_ERROR_TYPE_ILLEGAL_PHONE_NUMBER -> throw new IllegalArgumentException();
|
||||
default -> throw new RuntimeException(
|
||||
"Unrecognized error type from registration service: " + response.getError().getErrorType());
|
||||
}
|
||||
}
|
||||
|
||||
case RESPONSE_NOT_SET -> throw new RuntimeException("No response from registration service");
|
||||
};
|
||||
}
|
||||
|
||||
public CompletableFuture<RegistrationServiceSession> sendVerificationCode(final byte[] sessionId,
|
||||
public RegistrationServiceSession sendVerificationCode(final byte[] sessionId,
|
||||
final MessageTransport messageTransport,
|
||||
final ClientType clientType,
|
||||
@Nullable final String acceptLanguage,
|
||||
@Nullable final String senderOverride,
|
||||
final Duration timeout) {
|
||||
final Duration timeout)
|
||||
throws VerificationSessionRateLimitExceededException, RegistrationServiceException, RegistrationServiceSenderException, RegistrationFraudException {
|
||||
|
||||
final SendVerificationCodeRequest.Builder requestBuilder = SendVerificationCodeRequest.newBuilder()
|
||||
.setSessionId(ByteString.copyFrom(sessionId))
|
||||
@@ -153,100 +152,95 @@ public class RegistrationServiceClient implements Managed {
|
||||
requestBuilder.setSenderName(senderOverride);
|
||||
}
|
||||
|
||||
return CompletableFutureUtil.toCompletableFuture(stub.withDeadline(toDeadline(timeout))
|
||||
.sendVerificationCode(requestBuilder.build()), callbackExecutor)
|
||||
.thenApply(response -> {
|
||||
if (response.hasError()) {
|
||||
switch (response.getError().getErrorType()) {
|
||||
case SEND_VERIFICATION_CODE_ERROR_TYPE_RATE_LIMITED -> throw new CompletionException(
|
||||
new VerificationSessionRateLimitExceededException(
|
||||
buildSessionResponseFromMetadata(response.getSessionMetadata()),
|
||||
response.getError().getMayRetry()
|
||||
? Duration.ofSeconds(response.getError().getRetryAfterSeconds())
|
||||
: null,
|
||||
true));
|
||||
final SendVerificationCodeResponse response =
|
||||
stub.withDeadline(toDeadline(timeout)).sendVerificationCode(requestBuilder.build());
|
||||
|
||||
case SEND_VERIFICATION_CODE_ERROR_TYPE_SESSION_NOT_FOUND -> throw new CompletionException(
|
||||
new RegistrationServiceException(null));
|
||||
if (response.hasError()) {
|
||||
switch (response.getError().getErrorType()) {
|
||||
case SEND_VERIFICATION_CODE_ERROR_TYPE_RATE_LIMITED -> throw new VerificationSessionRateLimitExceededException(
|
||||
buildSessionResponseFromMetadata(response.getSessionMetadata()),
|
||||
response.getError().getMayRetry()
|
||||
? Duration.ofSeconds(response.getError().getRetryAfterSeconds())
|
||||
: null,
|
||||
true);
|
||||
|
||||
case SEND_VERIFICATION_CODE_ERROR_TYPE_SESSION_ALREADY_VERIFIED -> throw new CompletionException(
|
||||
new RegistrationServiceException(buildSessionResponseFromMetadata(response.getSessionMetadata())));
|
||||
case SEND_VERIFICATION_CODE_ERROR_TYPE_SESSION_NOT_FOUND -> throw new RegistrationServiceException(null);
|
||||
|
||||
case SEND_VERIFICATION_CODE_ERROR_TYPE_SENDER_REJECTED -> throw new CompletionException(
|
||||
RegistrationServiceSenderException.rejected(response.getError().getMayRetry()));
|
||||
case SEND_VERIFICATION_CODE_ERROR_TYPE_SUSPECTED_FRAUD ->
|
||||
throw new CompletionException(new RegistrationFraudException(
|
||||
RegistrationServiceSenderException.rejected(response.getError().getMayRetry())));
|
||||
case SEND_VERIFICATION_CODE_ERROR_TYPE_SENDER_ILLEGAL_ARGUMENT -> throw new CompletionException(
|
||||
RegistrationServiceSenderException.illegalArgument(response.getError().getMayRetry()));
|
||||
case SEND_VERIFICATION_CODE_ERROR_TYPE_UNSPECIFIED -> throw new CompletionException(
|
||||
RegistrationServiceSenderException.unknown(response.getError().getMayRetry()));
|
||||
case SEND_VERIFICATION_CODE_ERROR_TYPE_TRANSPORT_NOT_ALLOWED -> throw new CompletionException(
|
||||
new TransportNotAllowedException(buildSessionResponseFromMetadata(response.getSessionMetadata())));
|
||||
case SEND_VERIFICATION_CODE_ERROR_TYPE_SESSION_ALREADY_VERIFIED ->
|
||||
throw new RegistrationServiceException(buildSessionResponseFromMetadata(response.getSessionMetadata()));
|
||||
|
||||
default -> throw new CompletionException(
|
||||
new RuntimeException("Failed to send verification code: " + response.getError().getErrorType()));
|
||||
}
|
||||
} else {
|
||||
return buildSessionResponseFromMetadata(response.getSessionMetadata());
|
||||
}
|
||||
});
|
||||
case SEND_VERIFICATION_CODE_ERROR_TYPE_SENDER_REJECTED ->
|
||||
throw RegistrationServiceSenderException.rejected(response.getError().getMayRetry());
|
||||
|
||||
case SEND_VERIFICATION_CODE_ERROR_TYPE_SUSPECTED_FRAUD ->
|
||||
throw new RegistrationFraudException(
|
||||
RegistrationServiceSenderException.rejected(response.getError().getMayRetry()));
|
||||
|
||||
case SEND_VERIFICATION_CODE_ERROR_TYPE_SENDER_ILLEGAL_ARGUMENT ->
|
||||
throw RegistrationServiceSenderException.illegalArgument(response.getError().getMayRetry());
|
||||
|
||||
case SEND_VERIFICATION_CODE_ERROR_TYPE_UNSPECIFIED ->
|
||||
throw RegistrationServiceSenderException.unknown(response.getError().getMayRetry());
|
||||
|
||||
case SEND_VERIFICATION_CODE_ERROR_TYPE_TRANSPORT_NOT_ALLOWED ->
|
||||
throw new TransportNotAllowedException(buildSessionResponseFromMetadata(response.getSessionMetadata()));
|
||||
case SEND_VERIFICATION_CODE_ERROR_NO_SENDER_AVAILABLE ->
|
||||
throw RegistrationServiceSenderException.unavailable(response.getError().getMayRetry());
|
||||
|
||||
default -> throw new RuntimeException("Failed to send verification code: " + response.getError().getErrorType());
|
||||
}
|
||||
} else {
|
||||
return buildSessionResponseFromMetadata(response.getSessionMetadata());
|
||||
}
|
||||
}
|
||||
|
||||
public CompletableFuture<RegistrationServiceSession> checkVerificationCode(final byte[] sessionId,
|
||||
public RegistrationServiceSession checkVerificationCode(final byte[] sessionId,
|
||||
final String verificationCode,
|
||||
final Duration timeout) {
|
||||
return CompletableFutureUtil.toCompletableFuture(stub.withDeadline(toDeadline(timeout))
|
||||
final Duration timeout) throws VerificationSessionRateLimitExceededException, RegistrationServiceException {
|
||||
|
||||
final CheckVerificationCodeResponse response = stub.withDeadline(toDeadline(timeout))
|
||||
.checkVerificationCode(CheckVerificationCodeRequest.newBuilder()
|
||||
.setSessionId(ByteString.copyFrom(sessionId))
|
||||
.setVerificationCode(verificationCode)
|
||||
.build()), callbackExecutor)
|
||||
.thenApply(response -> {
|
||||
if (response.hasError()) {
|
||||
switch (response.getError().getErrorType()) {
|
||||
case CHECK_VERIFICATION_CODE_ERROR_TYPE_RATE_LIMITED -> throw new CompletionException(
|
||||
new VerificationSessionRateLimitExceededException(
|
||||
buildSessionResponseFromMetadata(response.getSessionMetadata()),
|
||||
response.getError().getMayRetry()
|
||||
? Duration.ofSeconds(response.getError().getRetryAfterSeconds())
|
||||
: null,
|
||||
true));
|
||||
.build());
|
||||
|
||||
case CHECK_VERIFICATION_CODE_ERROR_TYPE_NO_CODE_SENT, CHECK_VERIFICATION_CODE_ERROR_TYPE_ATTEMPT_EXPIRED ->
|
||||
throw new CompletionException(
|
||||
new RegistrationServiceException(buildSessionResponseFromMetadata(response.getSessionMetadata()))
|
||||
);
|
||||
if (response.hasError()) {
|
||||
switch (response.getError().getErrorType()) {
|
||||
case CHECK_VERIFICATION_CODE_ERROR_TYPE_RATE_LIMITED -> throw new VerificationSessionRateLimitExceededException(
|
||||
buildSessionResponseFromMetadata(response.getSessionMetadata()),
|
||||
response.getError().getMayRetry()
|
||||
? Duration.ofSeconds(response.getError().getRetryAfterSeconds())
|
||||
: null,
|
||||
true);
|
||||
|
||||
case CHECK_VERIFICATION_CODE_ERROR_TYPE_SESSION_NOT_FOUND -> throw new CompletionException(
|
||||
new RegistrationServiceException(null)
|
||||
);
|
||||
case CHECK_VERIFICATION_CODE_ERROR_TYPE_NO_CODE_SENT, CHECK_VERIFICATION_CODE_ERROR_TYPE_ATTEMPT_EXPIRED ->
|
||||
throw new RegistrationServiceException(buildSessionResponseFromMetadata(response.getSessionMetadata()));
|
||||
|
||||
default -> throw new CompletionException(
|
||||
new RuntimeException("Failed to check verification code: " + response.getError().getErrorType()));
|
||||
}
|
||||
} else {
|
||||
return buildSessionResponseFromMetadata(response.getSessionMetadata());
|
||||
}
|
||||
});
|
||||
case CHECK_VERIFICATION_CODE_ERROR_TYPE_SESSION_NOT_FOUND -> throw new RegistrationServiceException(null);
|
||||
|
||||
default -> throw new RuntimeException("Failed to check verification code: " + response.getError().getErrorType());
|
||||
}
|
||||
} else {
|
||||
return buildSessionResponseFromMetadata(response.getSessionMetadata());
|
||||
}
|
||||
}
|
||||
|
||||
public CompletableFuture<Optional<RegistrationServiceSession>> getSession(final byte[] sessionId,
|
||||
final Duration timeout) {
|
||||
return CompletableFutureUtil.toCompletableFuture(stub.withDeadline(toDeadline(timeout)).getSessionMetadata(
|
||||
GetRegistrationSessionMetadataRequest.newBuilder()
|
||||
.setSessionId(ByteString.copyFrom(sessionId)).build()), callbackExecutor)
|
||||
.thenApply(response -> {
|
||||
if (response.hasError()) {
|
||||
switch (response.getError().getErrorType()) {
|
||||
case GET_REGISTRATION_SESSION_METADATA_ERROR_TYPE_NOT_FOUND -> {
|
||||
return Optional.empty();
|
||||
}
|
||||
default -> throw new RuntimeException("Failed to get session: " + response.getError().getErrorType());
|
||||
}
|
||||
}
|
||||
public Optional<RegistrationServiceSession> getSession(final byte[] sessionId, final Duration timeout) {
|
||||
final GetRegistrationSessionMetadataResponse response = stub.withDeadline(toDeadline(timeout))
|
||||
.getSessionMetadata(GetRegistrationSessionMetadataRequest.newBuilder()
|
||||
.setSessionId(ByteString.copyFrom(sessionId)).build());
|
||||
|
||||
return Optional.of(buildSessionResponseFromMetadata(response.getSessionMetadata()));
|
||||
});
|
||||
if (response.hasError()) {
|
||||
switch (response.getError().getErrorType()) {
|
||||
case GET_REGISTRATION_SESSION_METADATA_ERROR_TYPE_NOT_FOUND -> {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
default -> throw new RuntimeException("Failed to get session: " + response.getError().getErrorType());
|
||||
}
|
||||
}
|
||||
|
||||
return Optional.of(buildSessionResponseFromMetadata(response.getSessionMetadata()));
|
||||
}
|
||||
|
||||
private static RegistrationServiceSession buildSessionResponseFromMetadata(
|
||||
@@ -286,7 +280,7 @@ public class RegistrationServiceClient implements Managed {
|
||||
}
|
||||
}
|
||||
|
||||
private String hmac(String sourceHost) {
|
||||
private String hmac(final String sourceHost) {
|
||||
final Mac hmacSha256 = getInitializedMac();
|
||||
hmacSha256.update(sourceHost.getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
@@ -301,7 +295,6 @@ public class RegistrationServiceClient implements Managed {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private static Mac getInitializedMac(byte[] key) throws InvalidKeyException {
|
||||
try {
|
||||
final Mac hmacSha256 = Mac.getInstance("HmacSHA256");
|
||||
|
||||
+4
@@ -28,6 +28,10 @@ public class RegistrationServiceSenderException extends Exception {
|
||||
return new RegistrationServiceSenderException(Reason.PROVIDER_UNAVAILABLE, permanent);
|
||||
}
|
||||
|
||||
public static RegistrationServiceSenderException unavailable(final boolean permanent) {
|
||||
return new RegistrationServiceSenderException(Reason.PROVIDER_UNAVAILABLE, permanent);
|
||||
}
|
||||
|
||||
private RegistrationServiceSenderException(final Reason reason, final boolean permanent) {
|
||||
super(null, null, true, false);
|
||||
this.reason = reason;
|
||||
|
||||
@@ -1,64 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2020 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.s3;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.InvalidKeyException;
|
||||
import java.security.Key;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.HexFormat;
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
|
||||
public class PolicySigner {
|
||||
|
||||
private final String awsAccessSecret;
|
||||
private final String region;
|
||||
|
||||
private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern("yyyyMMdd");
|
||||
|
||||
public PolicySigner(final String awsAccessSecret, final String region) {
|
||||
this.awsAccessSecret = awsAccessSecret;
|
||||
this.region = region;
|
||||
}
|
||||
|
||||
// See https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_sigv-create-signed-request.html
|
||||
public String getSignature(final ZonedDateTime now, final String policy) {
|
||||
final Mac mac;
|
||||
|
||||
try {
|
||||
mac = Mac.getInstance("HmacSHA256");
|
||||
} catch (final NoSuchAlgorithmException e) {
|
||||
throw new AssertionError("Every implementation of the Java platform is required to support HmacSHA256", e);
|
||||
}
|
||||
|
||||
try {
|
||||
mac.init(toHmacKey(("AWS4" + awsAccessSecret).getBytes(StandardCharsets.UTF_8)));
|
||||
final byte[] dateKey = mac.doFinal(now.format(DATE_FORMAT).getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
mac.init(toHmacKey(dateKey));
|
||||
final byte[] dateRegionKey = mac.doFinal(region.getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
mac.init(toHmacKey(dateRegionKey));
|
||||
final byte[] dateRegionServiceKey = mac.doFinal("s3".getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
mac.init(toHmacKey(dateRegionServiceKey));
|
||||
final byte[] signingKey = mac.doFinal("aws4_request".getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
mac.init(toHmacKey(signingKey));
|
||||
|
||||
return HexFormat.of().formatHex(mac.doFinal(policy.getBytes(StandardCharsets.UTF_8)));
|
||||
} catch (final InvalidKeyException e) {
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
}
|
||||
|
||||
private static Key toHmacKey(final byte[] bytes) {
|
||||
return new SecretKeySpec(bytes, "HmacSHA256");
|
||||
}
|
||||
}
|
||||
+70
-11
@@ -5,31 +5,52 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.s3;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.InvalidKeyException;
|
||||
import java.security.Key;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.Base64;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import java.util.HexFormat;
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
|
||||
public class PostPolicyGenerator {
|
||||
|
||||
public static final DateTimeFormatter AWS_DATE_TIME = DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmssX");
|
||||
private static final DateTimeFormatter CREDENTIAL_DATE = DateTimeFormatter.ofPattern("yyyyMMdd");
|
||||
public static final String ALGORITHM = "AWS4-HMAC-SHA256";
|
||||
public static final String ACL = "private";
|
||||
|
||||
private static final DateTimeFormatter AWS_TIMESTAMP_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmssX");
|
||||
private static final DateTimeFormatter AWS_DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd");
|
||||
|
||||
private final String region;
|
||||
private final String bucket;
|
||||
private final String awsAccessId;
|
||||
private final String awsAccessSecret;
|
||||
|
||||
public record SignedPostPolicy(String formattedTimestamp, String credential, String encodedPolicy, String signature) {
|
||||
}
|
||||
|
||||
public PostPolicyGenerator(final String region,
|
||||
final String bucket,
|
||||
final String awsAccessId,
|
||||
final String awsAccessSecret) {
|
||||
|
||||
public PostPolicyGenerator(final String region, final String bucket, final String awsAccessId) {
|
||||
this.region = region;
|
||||
this.bucket = bucket;
|
||||
this.awsAccessId = awsAccessId;
|
||||
this.awsAccessSecret = awsAccessSecret;
|
||||
}
|
||||
|
||||
public Pair<String, String> createFor(final ZonedDateTime now, final String object, final int maxSizeInBytes) {
|
||||
public SignedPostPolicy createFor(final String object, final int maxSizeInBytes, final Instant currentTime) {
|
||||
final ZonedDateTime now = ZonedDateTime.ofInstant(currentTime, ZoneOffset.UTC);
|
||||
final String expiration = now.plusMinutes(30).format(DateTimeFormatter.ISO_INSTANT);
|
||||
final String credentialDate = now.format(CREDENTIAL_DATE);
|
||||
final String requestDate = now.format(AWS_DATE_TIME);
|
||||
final String credentialDate = now.format(AWS_DATE_FORMATTER);
|
||||
final String requestTimestamp = now.format(AWS_TIMESTAMP_FORMATTER);
|
||||
final String credential = String.format("%s/%s/%s/s3/aws4_request", awsAccessId, credentialDate, region);
|
||||
|
||||
final String policy = String.format("""
|
||||
@@ -38,17 +59,55 @@ public class PostPolicyGenerator {
|
||||
"conditions": [
|
||||
{"bucket": "%s"},
|
||||
{"key": "%s"},
|
||||
{"acl": "private"},
|
||||
{"acl": "%s"},
|
||||
["starts-with", "$Content-Type", ""],
|
||||
["content-length-range", 1, %d],
|
||||
|
||||
{"x-amz-credential": "%s"},
|
||||
{"x-amz-algorithm": "AWS4-HMAC-SHA256"},
|
||||
{"x-amz-algorithm": "%s"},
|
||||
{"x-amz-date": "%s" }
|
||||
]
|
||||
}
|
||||
""", expiration, bucket, object, maxSizeInBytes, credential, requestDate);
|
||||
""", expiration, bucket, object, ACL, maxSizeInBytes, credential, ALGORITHM, requestTimestamp);
|
||||
|
||||
return new Pair<>(credential, Base64.getEncoder().encodeToString(policy.getBytes(StandardCharsets.UTF_8)));
|
||||
final String encodedPolicy = Base64.getEncoder().encodeToString(policy.getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
return new SignedPostPolicy(requestTimestamp, credential, encodedPolicy, getSignature(now, encodedPolicy));
|
||||
}
|
||||
|
||||
// See https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_sigv-create-signed-request.html
|
||||
@VisibleForTesting
|
||||
String getSignature(final ZonedDateTime now, final String policy) {
|
||||
final Mac mac;
|
||||
|
||||
try {
|
||||
mac = Mac.getInstance("HmacSHA256");
|
||||
} catch (final NoSuchAlgorithmException e) {
|
||||
throw new AssertionError("Every implementation of the Java platform is required to support HmacSHA256", e);
|
||||
}
|
||||
|
||||
try {
|
||||
mac.init(toHmacKey(("AWS4" + awsAccessSecret).getBytes(StandardCharsets.UTF_8)));
|
||||
final byte[] dateKey = mac.doFinal(now.format(AWS_DATE_FORMATTER).getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
mac.init(toHmacKey(dateKey));
|
||||
final byte[] dateRegionKey = mac.doFinal(region.getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
mac.init(toHmacKey(dateRegionKey));
|
||||
final byte[] dateRegionServiceKey = mac.doFinal("s3".getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
mac.init(toHmacKey(dateRegionServiceKey));
|
||||
final byte[] signingKey = mac.doFinal("aws4_request".getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
mac.init(toHmacKey(signingKey));
|
||||
|
||||
return HexFormat.of().formatHex(mac.doFinal(policy.getBytes(StandardCharsets.UTF_8)));
|
||||
} catch (final InvalidKeyException e) {
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
}
|
||||
|
||||
private static Key toHmacKey(final byte[] bytes) {
|
||||
return new SecretKeySpec(bytes, "HmacSHA256");
|
||||
}
|
||||
}
|
||||
@@ -9,12 +9,9 @@ import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
import com.fasterxml.jackson.annotation.JsonFilter;
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.core.JsonGenerator;
|
||||
import com.fasterxml.jackson.core.JsonParser;
|
||||
import com.fasterxml.jackson.databind.DeserializationContext;
|
||||
import com.fasterxml.jackson.databind.JsonDeserializer;
|
||||
import com.fasterxml.jackson.databind.JsonSerializer;
|
||||
import com.fasterxml.jackson.databind.SerializerProvider;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
@@ -33,6 +30,7 @@ import java.util.UUID;
|
||||
import javax.annotation.Nullable;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.signal.libsignal.zkgroup.ZkCredentialPublicKey;
|
||||
import org.signal.libsignal.zkgroup.backups.BackupCredentialType;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
@@ -43,6 +41,7 @@ import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.util.ByteArrayBase64UrlAdapter;
|
||||
import org.whispersystems.textsecuregcm.util.IdentityKeyAdapter;
|
||||
import org.whispersystems.textsecuregcm.util.ZkCredentialPublicKeyAdapter;
|
||||
|
||||
@JsonFilter("Account")
|
||||
public class Account {
|
||||
@@ -128,7 +127,9 @@ public class Account {
|
||||
|
||||
@JsonProperty("zck")
|
||||
@Nullable
|
||||
private byte[] zkCredentialKey;
|
||||
@JsonSerialize(using = ZkCredentialPublicKeyAdapter.Serializer.class)
|
||||
@JsonDeserialize(using = ZkCredentialPublicKeyAdapter.Deserializer.class)
|
||||
private ZkCredentialPublicKey zkCredentialKey;
|
||||
|
||||
@JsonProperty("zckr")
|
||||
@Nullable
|
||||
@@ -560,12 +561,11 @@ public class Account {
|
||||
this.usernameHolds = usernameHolds;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public byte[] getZkCredentialKey() {
|
||||
return zkCredentialKey;
|
||||
public Optional<ZkCredentialPublicKey> getZkCredentialKey() {
|
||||
return Optional.ofNullable(zkCredentialKey);
|
||||
}
|
||||
|
||||
public void setZkCredentialKey(@Nullable final byte[] zkCredentialKey) {
|
||||
public void setZkCredentialKey(@Nullable final ZkCredentialPublicKey zkCredentialKey) {
|
||||
this.zkCredentialKey = zkCredentialKey;
|
||||
}
|
||||
|
||||
|
||||
@@ -327,7 +327,8 @@ public class Accounts {
|
||||
accountToCreate.setBackupVoucher(existingAccount.getBackupVoucher());
|
||||
|
||||
// Carry over the existing ZK credential key to the new account
|
||||
accountToCreate.setZkCredentialKey(existingAccount.getZkCredentialKey());
|
||||
accountToCreate.setZkCredentialKey(existingAccount.getZkCredentialKey().orElse(null));
|
||||
accountToCreate.setZkCredentialKeyRotationId(existingAccount.getZkCredentialKeyRotationId());
|
||||
|
||||
final List<TransactWriteItem> writeItems = new ArrayList<>();
|
||||
|
||||
|
||||
+162
@@ -0,0 +1,162 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Flow;
|
||||
import java.util.function.BiConsumer;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import org.reactivestreams.Subscription;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStream;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
import reactor.adapter.JdkFlowAdapter;
|
||||
import reactor.core.publisher.BaseSubscriber;
|
||||
|
||||
/// A temporary message stream that can mirror message acknowledgements (deletion requests) to FoundationDB
|
||||
public class AcknowledgementMirroringMessageStream implements MessageStream {
|
||||
|
||||
private final RedisDynamoDbMessageStream redisDynamoDbMessageStream;
|
||||
private final FoundationDbMessageStream foundationDbMessageStream;
|
||||
|
||||
private final Set<UUID> messagesPendingAcknowledgement = new HashSet<>();
|
||||
|
||||
private static final int HIGH_PENDING_ACKNOWLEDGEMENT_COUNT_WARNING_THRESHOLD = 1024;
|
||||
|
||||
@VisibleForTesting
|
||||
static final int MAX_PENDING_ACKNOWLEDGEMENTS = 8192;
|
||||
|
||||
@VisibleForTesting
|
||||
static final int FOUNDATIONDB_REQUEST_SIZE = 100;
|
||||
|
||||
private static final Counter HIGH_PENDING_ACKNOWLEDGEMENT_COUNT_WARNING_COUNTER =
|
||||
Metrics.counter(MetricsUtil.name(AcknowledgementMirroringMessageStream.class, "highPendingAcknowledgementCount"));
|
||||
|
||||
private static final Counter MAX_PENDING_ACKNOWLEDGEMENT_LIMIT_BREACHED_COUNTER =
|
||||
Metrics.counter(MetricsUtil.name(AcknowledgementMirroringMessageStream.class, "maxPendingAcknowledgementLimitBreached"));
|
||||
|
||||
private static class FoundationDbSubscriber extends BaseSubscriber<MessageStreamEntry.Envelope> {
|
||||
|
||||
private final BiConsumer<UUID, Long> mirroredMessageHandler;
|
||||
|
||||
private long mirroredEntriesDelivered = 0;
|
||||
private long requested = 0;
|
||||
|
||||
private FoundationDbSubscriber(final BiConsumer<UUID, Long> mirroredMessageHandler) {
|
||||
this.mirroredMessageHandler = mirroredMessageHandler;
|
||||
}
|
||||
|
||||
public void handleRedisDynamoDbMessageStreamEntry(final MessageStreamEntry messageStreamEntry) {
|
||||
final boolean isMirroredMessage = switch (messageStreamEntry) {
|
||||
case MessageStreamEntry.Envelope envelopeEntry ->
|
||||
UUIDUtil.fromByteString(envelopeEntry.message().getServerGuid()).version() == 8;
|
||||
|
||||
case MessageStreamEntry.QueueEmpty _ -> false;
|
||||
};
|
||||
|
||||
if (!isMirroredMessage) {
|
||||
return;
|
||||
}
|
||||
|
||||
final boolean requestMore;
|
||||
|
||||
synchronized (this) {
|
||||
requestMore = ++mirroredEntriesDelivered > requested;
|
||||
|
||||
if (requestMore) {
|
||||
requested += FOUNDATIONDB_REQUEST_SIZE;
|
||||
}
|
||||
}
|
||||
|
||||
if (requestMore) {
|
||||
request(FOUNDATIONDB_REQUEST_SIZE);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void hookOnSubscribe(final Subscription subscription) {
|
||||
// The base `hookOnSubscribe` requests `Long.MAX_VALUE` elements, and that is something we're explicitly trying
|
||||
// to avoid with this subscriber
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void hookOnNext(final MessageStreamEntry.Envelope envelope) {
|
||||
mirroredMessageHandler.accept(
|
||||
UUIDUtil.fromByteString(envelope.message().getServerGuid()), envelope.message().getServerTimestamp());
|
||||
}
|
||||
}
|
||||
|
||||
public AcknowledgementMirroringMessageStream(final RedisDynamoDbMessageStream redisDynamoDbMessageStream,
|
||||
final FoundationDbMessageStream foundationDbMessageStream) {
|
||||
|
||||
this.redisDynamoDbMessageStream = redisDynamoDbMessageStream;
|
||||
this.foundationDbMessageStream = foundationDbMessageStream;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Flow.Publisher<MessageStreamEntry> getMessages() {
|
||||
final FoundationDbSubscriber subscriber = new FoundationDbSubscriber(this::handleMirroredMessageAcknowledged);
|
||||
|
||||
JdkFlowAdapter.flowPublisherToFlux(foundationDbMessageStream.getMessages())
|
||||
.filter(messageStreamEntry -> messageStreamEntry instanceof MessageStreamEntry.Envelope)
|
||||
.cast(MessageStreamEntry.Envelope.class)
|
||||
.subscribe(subscriber);
|
||||
|
||||
return JdkFlowAdapter.publisherToFlowPublisher(
|
||||
JdkFlowAdapter.flowPublisherToFlux(redisDynamoDbMessageStream.getMessages())
|
||||
// Mirror demand and termination signals to the FoundationDB message stream
|
||||
.doOnNext(subscriber::handleRedisDynamoDbMessageStreamEntry)
|
||||
.doFinally(_ -> subscriber.dispose()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Void> acknowledgeMessage(final UUID messageGuid, final long serverTimestamp) {
|
||||
// All messages stored in FoundationDB use version 8 UUIDs; if a message has a version 4 UUID, then it only exists
|
||||
// in Redis/DynamoDB
|
||||
if (messageGuid.version() == 8) {
|
||||
handleMirroredMessageAcknowledged(messageGuid, serverTimestamp);
|
||||
}
|
||||
|
||||
return redisDynamoDbMessageStream.acknowledgeMessage(messageGuid, serverTimestamp);
|
||||
}
|
||||
|
||||
private void handleMirroredMessageAcknowledged(final UUID messageGuid, final long serverTimestamp) {
|
||||
// Before we can acknowledge and delete the message in FoundationDB, two things need to happen:
|
||||
//
|
||||
// 1. The client needs to acknowledge the message on the Redis/DDB stream.
|
||||
// 2. The message needs to pass through the FoundationDB message stream pipeline because it needs to be registered
|
||||
// in the acknowledged message buffer machinery before it can be deleted.
|
||||
//
|
||||
// We can't guarantee the order in which these two things happen, so we use a synchronized set to coordinate and
|
||||
// determine when both have happened.
|
||||
synchronized (messagesPendingAcknowledgement) {
|
||||
if (messagesPendingAcknowledgement.remove(messageGuid)) {
|
||||
// One of the two streams had already acknowledged this message, and this is the second acknowledgement. Now we
|
||||
// can pass the acknowledgement along to FoundationDB.
|
||||
foundationDbMessageStream.acknowledgeMessage(messageGuid, serverTimestamp);
|
||||
} else {
|
||||
// Either this message came from FoundationDB and got auto-acknowledged before getting explicitly acknowledged
|
||||
// on the Redis/DynamoDB stream or the message got explicitly acknowledged on the Redis/DynamoDB stream before
|
||||
// passing through the FoundationDB stream. Either way, wait for both streams to have done their part.
|
||||
if (messagesPendingAcknowledgement.add(messageGuid)) {
|
||||
if (messagesPendingAcknowledgement.size() == HIGH_PENDING_ACKNOWLEDGEMENT_COUNT_WARNING_THRESHOLD) {
|
||||
HIGH_PENDING_ACKNOWLEDGEMENT_COUNT_WARNING_COUNTER.increment();
|
||||
}
|
||||
|
||||
if (messagesPendingAcknowledgement.size() > MAX_PENDING_ACKNOWLEDGEMENTS) {
|
||||
MAX_PENDING_ACKNOWLEDGEMENT_LIMIT_BREACHED_COUNTER.increment();
|
||||
throw new IllegalStateException("Too many pending acknowledgements");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+17
-14
@@ -158,21 +158,24 @@ public class ChangeNumberManager {
|
||||
final Account updatedAccount = accountsManager.changeNumber(
|
||||
account.getIdentifier(IdentityType.ACI), number, pniIdentityKey, deviceSignedPreKeys, devicePqLastResortPreKeys, pniRegistrationIds);
|
||||
|
||||
try {
|
||||
// Now that we've actually updated the account, populate the "updated PNI" field on all envelopes
|
||||
messagesByDeviceId.replaceAll((_, envelope) ->
|
||||
envelope.toBuilder().setUpdatedPni(UUIDUtil.toByteString(updatedAccount.getIdentifier(IdentityType.PNI)))
|
||||
.build());
|
||||
if (!messagesByDeviceId.isEmpty()) {
|
||||
try {
|
||||
// Now that we've actually updated the account, populate the "updated PNI" field on all envelopes
|
||||
messagesByDeviceId.replaceAll((_, envelope) ->
|
||||
envelope.toBuilder().setUpdatedPni(UUIDUtil.toByteString(updatedAccount.getIdentifier(IdentityType.PNI)))
|
||||
.build());
|
||||
|
||||
messageSender.sendMessages(updatedAccount,
|
||||
serviceIdentifier,
|
||||
messagesByDeviceId,
|
||||
registrationIdsByDeviceId,
|
||||
Optional.of(Device.PRIMARY_ID),
|
||||
senderUserAgent);
|
||||
} catch (final RuntimeException e) {
|
||||
logger.warn("Changed number but could not send all device messages for {}", account.getIdentifier(IdentityType.ACI), e);
|
||||
throw e;
|
||||
messageSender.sendMessages(updatedAccount,
|
||||
serviceIdentifier,
|
||||
messagesByDeviceId,
|
||||
registrationIdsByDeviceId,
|
||||
Optional.of(Device.PRIMARY_ID),
|
||||
senderUserAgent);
|
||||
} catch (final RuntimeException e) {
|
||||
logger.warn("Changed number but could not send all device messages for {}",
|
||||
account.getIdentifier(IdentityType.ACI), e);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
return updatedAccount;
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.util.AttributeValues.b;
|
||||
import static org.whispersystems.textsecuregcm.util.AttributeValues.n;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Map;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ConditionalCheckFailedException;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ReturnValue;
|
||||
import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest;
|
||||
|
||||
public class DonationPermits {
|
||||
|
||||
public static final String KEY_SPEND_ID = "I"; // B (HashKey)
|
||||
public static final String KEY_EXPIRATION = "E"; // N
|
||||
|
||||
private final String table;
|
||||
private final Duration expiration;
|
||||
private final DynamoDbClient dynamoDbClient;
|
||||
|
||||
public DonationPermits(String tableName, Duration expiration,
|
||||
DynamoDbClient dynamoDbClient) {
|
||||
this.table = tableName;
|
||||
this.expiration = expiration;
|
||||
this.dynamoDbClient = dynamoDbClient;
|
||||
}
|
||||
|
||||
public boolean spend(final byte[] spendId, final Instant now) {
|
||||
final UpdateItemRequest updateItemRequest = UpdateItemRequest.builder()
|
||||
.tableName(table)
|
||||
.key(Map.of(KEY_SPEND_ID, b(spendId)))
|
||||
.conditionExpression("attribute_not_exists(#id)")
|
||||
.returnValues(ReturnValue.NONE)
|
||||
.updateExpression("SET #exp = :exp")
|
||||
.expressionAttributeNames(Map.of(
|
||||
"#id", KEY_SPEND_ID,
|
||||
"#exp", KEY_EXPIRATION))
|
||||
.expressionAttributeValues(Map.of(
|
||||
":exp", n(now.plus(expiration).getEpochSecond())))
|
||||
.build();
|
||||
try {
|
||||
dynamoDbClient.updateItem(updateItemRequest);
|
||||
|
||||
return true;
|
||||
} catch (final ConditionalCheckFailedException _) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import java.time.Clock;
|
||||
import org.signal.libsignal.zkgroup.ServerSecretParams;
|
||||
import org.signal.libsignal.zkgroup.VerificationFailedException;
|
||||
import org.signal.libsignal.zkgroup.donation.DonationPermit;
|
||||
import org.signal.libsignal.zkgroup.donation.DonationPermitDerivedKeyPair;
|
||||
import org.signal.libsignal.zkgroup.donation.DonationPermitRequest;
|
||||
import org.signal.libsignal.zkgroup.donation.DonationPermitResponse;
|
||||
|
||||
public class DonationPermitsManager {
|
||||
|
||||
private final DonationPermits donationPermits;
|
||||
private final ServerSecretParams serverSecretParams;
|
||||
private final Clock clock;
|
||||
|
||||
public DonationPermitsManager(final DonationPermits donationPermits, final ServerSecretParams serverSecretParams,
|
||||
final Clock clock) {
|
||||
this.donationPermits = donationPermits;
|
||||
this.serverSecretParams = serverSecretParams;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
/// Verifies and then spends the given {@link DonationPermit}
|
||||
///
|
||||
/// @return whether the spend was successful
|
||||
/// @throws VerificationFailedException if the permit was not valid (expired or otherwise)
|
||||
public boolean spend(final DonationPermit donationPermit) throws VerificationFailedException {
|
||||
// Permits must be verified with the key pair that issued them, which can be re-derived from the embedded expiration
|
||||
final DonationPermitDerivedKeyPair issuingKeyPair = DonationPermitDerivedKeyPair.forExpiration(
|
||||
donationPermit.getExpiration(), serverSecretParams);
|
||||
|
||||
donationPermit.verify(issuingKeyPair, clock.instant());
|
||||
|
||||
return donationPermits.spend(donationPermit.getSpendId(), clock.instant());
|
||||
}
|
||||
|
||||
/// Issues {@link DonationPermitResponse} with an expiration derived from the current time
|
||||
public DonationPermitResponse issue(final DonationPermitRequest permitRequest) {
|
||||
final DonationPermitDerivedKeyPair currentDerivedKeyPair = DonationPermitDerivedKeyPair.forExpiration(
|
||||
DonationPermitResponse.defaultExpiration(clock.instant()),
|
||||
serverSecretParams);
|
||||
|
||||
return permitRequest.issue(currentDerivedKeyPair);
|
||||
}
|
||||
|
||||
}
|
||||
+1
-1
@@ -350,7 +350,7 @@ public class MessagePersister implements Managed {
|
||||
cachedMessageBytes.set(estimatedPersistedQueueSize);
|
||||
targetDeleteBytes.set(Math.round(estimatedPersistedQueueSize * extraRoomRatio));
|
||||
|
||||
return Flux.from(messagesManager.getMessagesForDeviceReactive(aci, device, false))
|
||||
return Flux.from(messagesManager.getMessagesForDevice(aci, device))
|
||||
.concatMap(envelope -> {
|
||||
if (bytesDeleted.getAndAdd(envelope.getSerializedSize()) >= targetDeleteBytes.get()) {
|
||||
return Mono.just(Optional.<MessageProtos.Envelope>empty());
|
||||
|
||||
@@ -8,7 +8,6 @@ package org.whispersystems.textsecuregcm.storage;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Flow;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
|
||||
/// A message stream publishes an ordered stream of Signal messages from a destination device's queue and provides a
|
||||
/// mechanism for consumers to acknowledge receipt of delivered messages.
|
||||
|
||||
+155
-50
@@ -6,11 +6,14 @@ package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.protobuf.ByteString;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
@@ -23,17 +26,18 @@ import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
import javax.annotation.Nullable;
|
||||
import org.reactivestreams.Publisher;
|
||||
import org.signal.libsignal.protocol.SealedSenderMultiRecipientMessage;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStore;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
import reactor.core.observability.micrometer.Micrometer;
|
||||
import reactor.core.publisher.Flux;
|
||||
@@ -41,7 +45,6 @@ import reactor.core.publisher.Mono;
|
||||
|
||||
public class MessagesManager {
|
||||
|
||||
private static final int RESULT_SET_CHUNK_SIZE = 100;
|
||||
final String GET_MESSAGES_FOR_DEVICE_FLUX_NAME = name(MessagesManager.class, "getMessagesForDevice");
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(MessagesManager.class);
|
||||
@@ -55,27 +58,50 @@ public class MessagesManager {
|
||||
private static final String MAY_HAVE_MESSAGES_COUNTER_NAME =
|
||||
MetricsUtil.name(MessagesManager.class, "mayHaveMessages");
|
||||
|
||||
private static final String PRESENCE_MATCH_COUNTER_NAME =
|
||||
MetricsUtil.name(MessagesManager.class, "presenceMatch");
|
||||
|
||||
private static final Counter INSERT_TIMEOUT_COUNTER =
|
||||
Metrics.counter(name(MessagesManager.class, "insertTimeout"));
|
||||
|
||||
@VisibleForTesting
|
||||
static final String MIRROR_INSERTS_EXPERIMENT_NAME = "foundationDbMirrorInserts";
|
||||
|
||||
@VisibleForTesting
|
||||
static final String MIRROR_DELETIONS_EXPERIMENT_NAME = "foundationDbMirrorDeletions";
|
||||
|
||||
@VisibleForTesting
|
||||
static final String MIRROR_READS_EXPERIMENT_NAME = "foundationDbMirrorReads";
|
||||
|
||||
private static final long FOUNDATIONDB_INSERT_TIMEOUT_MILLIS = Duration.ofSeconds(2).toMillis();
|
||||
|
||||
private final MessagesDynamoDb messagesDynamoDb;
|
||||
private final MessagesCache messagesCache;
|
||||
private final FoundationDbMessageStore foundationDbMessageStore;
|
||||
private final RedisMessageAvailabilityManager redisMessageAvailabilityManager;
|
||||
private final ReportMessageManager reportMessageManager;
|
||||
private final ExecutorService messageDeletionExecutor;
|
||||
private final Clock clock;
|
||||
private final ExperimentEnrollmentManager experimentEnrollmentManager;
|
||||
|
||||
public MessagesManager(
|
||||
final MessagesDynamoDb messagesDynamoDb,
|
||||
final MessagesCache messagesCache,
|
||||
final FoundationDbMessageStore foundationDbMessageStore,
|
||||
final RedisMessageAvailabilityManager redisMessageAvailabilityManager,
|
||||
final ReportMessageManager reportMessageManager,
|
||||
final ExecutorService messageDeletionExecutor,
|
||||
final Clock clock) {
|
||||
final Clock clock,
|
||||
final ExperimentEnrollmentManager experimentEnrollmentManager) {
|
||||
|
||||
this.messagesDynamoDb = messagesDynamoDb;
|
||||
this.messagesCache = messagesCache;
|
||||
this.foundationDbMessageStore = foundationDbMessageStore;
|
||||
this.redisMessageAvailabilityManager = redisMessageAvailabilityManager;
|
||||
this.reportMessageManager = reportMessageManager;
|
||||
this.messageDeletionExecutor = messageDeletionExecutor;
|
||||
this.clock = clock;
|
||||
this.experimentEnrollmentManager = experimentEnrollmentManager;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -95,28 +121,72 @@ public class MessagesManager {
|
||||
private CompletableFuture<Map<Byte, Boolean>> insertAsync(final UUID accountIdentifier, final Map<Byte, Envelope> messagesByDeviceId) {
|
||||
final Map<Byte, Boolean> devicePresenceById = new ConcurrentHashMap<>();
|
||||
|
||||
return CompletableFuture.allOf(messagesByDeviceId.entrySet().stream()
|
||||
.map(deviceIdAndMessage -> {
|
||||
final byte deviceId = deviceIdAndMessage.getKey();
|
||||
final Envelope message = deviceIdAndMessage.getValue();
|
||||
final UUID messageGuid = UUID.randomUUID();
|
||||
final CompletableFuture<Map<Byte, FoundationDbMessageStore.InsertResult>> foundationDbInsertFuture;
|
||||
|
||||
return messagesCache.insert(messageGuid, accountIdentifier, deviceId, message)
|
||||
.thenAccept(present -> {
|
||||
if (message.hasSourceServiceId()) {
|
||||
final ServiceIdentifier sourceServiceIdentifier =
|
||||
ServiceIdentifier.fromByteString(message.getSourceServiceId());
|
||||
if (experimentEnrollmentManager.isEnrolled(accountIdentifier, MIRROR_INSERTS_EXPERIMENT_NAME)) {
|
||||
// Multi-recipient messages will have both a "shared MRM key" and actual message content; we only need/want the
|
||||
// latter for FoundationDB
|
||||
final Map<Byte, Envelope> minimizedMessagesByDeviceId = messagesByDeviceId.entrySet().stream()
|
||||
.collect(Collectors.toUnmodifiableMap(
|
||||
Map.Entry::getKey,
|
||||
entry -> entry.getValue().toBuilder().clearSharedMrmKey().build()));
|
||||
|
||||
if (!accountIdentifier.equals(sourceServiceIdentifier.uuid())) {
|
||||
// Note that this is an asynchronous, best-effort, fire-and-forget operation
|
||||
reportMessageManager.store(sourceServiceIdentifier.toServiceIdentifierString(), messageGuid);
|
||||
}
|
||||
}
|
||||
foundationDbInsertFuture =
|
||||
foundationDbMessageStore.insert(new AciServiceIdentifier(accountIdentifier), minimizedMessagesByDeviceId)
|
||||
.orTimeout(FOUNDATIONDB_INSERT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)
|
||||
.exceptionally(e -> {
|
||||
if (e instanceof TimeoutException) {
|
||||
INSERT_TIMEOUT_COUNTER.increment();
|
||||
} else {
|
||||
logger.warn("Failed to insert {} message(s) for {} into FoundationDB",
|
||||
minimizedMessagesByDeviceId.size(),
|
||||
accountIdentifier,
|
||||
e);
|
||||
}
|
||||
|
||||
devicePresenceById.put(deviceId, present);
|
||||
});
|
||||
})
|
||||
.toArray(CompletableFuture[]::new))
|
||||
return Collections.emptyMap();
|
||||
});
|
||||
} else {
|
||||
foundationDbInsertFuture = CompletableFuture.completedFuture(Collections.emptyMap());
|
||||
}
|
||||
|
||||
return foundationDbInsertFuture.thenCompose(foundationDbInsertResults ->
|
||||
CompletableFuture.allOf(messagesByDeviceId.entrySet().stream()
|
||||
.map(deviceIdAndMessage -> {
|
||||
final byte deviceId = deviceIdAndMessage.getKey();
|
||||
|
||||
// Multi-recipient messages will have both a "shared MRM key" and actual message content; we only
|
||||
// need/want the former for Redis
|
||||
final Envelope message = deviceIdAndMessage.getValue().hasSharedMrmKey()
|
||||
? deviceIdAndMessage.getValue().toBuilder().clearContent().build()
|
||||
: deviceIdAndMessage.getValue();
|
||||
|
||||
final UUID messageGuid = Optional.ofNullable(foundationDbInsertResults.get(deviceId))
|
||||
.flatMap(FoundationDbMessageStore.InsertResult::messageGuid)
|
||||
.orElseGet(UUID::randomUUID);
|
||||
|
||||
return messagesCache.insert(messageGuid, accountIdentifier, deviceId, message)
|
||||
.thenAccept(present -> {
|
||||
if (message.hasSourceServiceId()) {
|
||||
final ServiceIdentifier sourceServiceIdentifier =
|
||||
ServiceIdentifier.fromByteString(message.getSourceServiceId());
|
||||
|
||||
if (!accountIdentifier.equals(sourceServiceIdentifier.uuid())) {
|
||||
// Note that this is an asynchronous, best-effort, fire-and-forget operation
|
||||
reportMessageManager.store(sourceServiceIdentifier.toServiceIdentifierString(), messageGuid);
|
||||
}
|
||||
}
|
||||
|
||||
devicePresenceById.put(deviceId, present);
|
||||
|
||||
if (foundationDbInsertResults.containsKey(deviceId)) {
|
||||
Metrics.counter(PRESENCE_MATCH_COUNTER_NAME,
|
||||
"match", String.valueOf(present == foundationDbInsertResults.get(deviceId).present()))
|
||||
.increment();
|
||||
}
|
||||
});
|
||||
})
|
||||
.toArray(CompletableFuture[]::new)))
|
||||
.thenApply(ignored -> devicePresenceById);
|
||||
}
|
||||
|
||||
@@ -176,6 +246,7 @@ public class MessagesManager {
|
||||
return insertAsync(resolvedRecipients.get(recipient).getIdentifier(IdentityType.ACI),
|
||||
IntStream.range(0, devices.length).mapToObj(i -> devices[i])
|
||||
.collect(Collectors.toMap(deviceId -> deviceId, _ -> prototypeMessage.toBuilder()
|
||||
.setContent(ByteString.copyFrom(multiRecipientMessage.messageForRecipient(serviceIdAndRecipient.getValue())))
|
||||
.setDestinationServiceId(serviceIdentifier.toCompactByteString())
|
||||
.build())))
|
||||
.thenAccept(clientPresenceByDeviceId ->
|
||||
@@ -217,43 +288,52 @@ public class MessagesManager {
|
||||
return messagesDynamoDb.mayHaveUrgentMessages(destinationUuid, destinationDevice);
|
||||
}
|
||||
|
||||
public Mono<Pair<List<Envelope>, Boolean>> getMessagesForDevice(UUID destinationUuid, Device destinationDevice,
|
||||
boolean cachedMessagesOnly) {
|
||||
|
||||
return Flux.from(
|
||||
getMessagesForDevice(destinationUuid, destinationDevice, RESULT_SET_CHUNK_SIZE, cachedMessagesOnly))
|
||||
.take(RESULT_SET_CHUNK_SIZE)
|
||||
.collectList()
|
||||
.map(envelopes -> new Pair<>(envelopes, envelopes.size() >= RESULT_SET_CHUNK_SIZE));
|
||||
}
|
||||
|
||||
public Publisher<Envelope> getMessagesForDeviceReactive(UUID destinationUuid, Device destinationDevice,
|
||||
final boolean cachedMessagesOnly) {
|
||||
|
||||
return getMessagesForDevice(destinationUuid, destinationDevice, null, cachedMessagesOnly);
|
||||
}
|
||||
|
||||
public MessageStream getMessages(final UUID destinationUuid, final Device destinationDevice) {
|
||||
return new RedisDynamoDbMessageStream(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, destinationUuid, destinationDevice);
|
||||
final RedisDynamoDbMessageStream redisDynamoDbMessageStream =
|
||||
new RedisDynamoDbMessageStream(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager,
|
||||
destinationUuid, destinationDevice);
|
||||
|
||||
return new MirroringMessageStream(
|
||||
redisDynamoDbMessageStream,
|
||||
foundationDbMessageStore.getMessages(new AciServiceIdentifier(destinationUuid), destinationDevice.getId()),
|
||||
experimentEnrollmentManager,
|
||||
destinationUuid,
|
||||
destinationDevice.getId());
|
||||
}
|
||||
|
||||
private Publisher<Envelope> getMessagesForDevice(UUID destinationUuid, Device destinationDevice,
|
||||
@Nullable Integer limit, final boolean cachedMessagesOnly) {
|
||||
|
||||
final Publisher<Envelope> dynamoPublisher =
|
||||
cachedMessagesOnly ? Flux.empty() : messagesDynamoDb.load(destinationUuid, destinationDevice, limit);
|
||||
final Publisher<Envelope> cachePublisher = messagesCache.get(destinationUuid, destinationDevice.getId());
|
||||
|
||||
return Flux.concat(dynamoPublisher, cachePublisher)
|
||||
Publisher<Envelope> getMessagesForDevice(final UUID destinationUuid, final Device destinationDevice) {
|
||||
return Flux.concat(
|
||||
messagesDynamoDb.load(destinationUuid, destinationDevice, null),
|
||||
messagesCache.get(destinationUuid, destinationDevice.getId()))
|
||||
.name(GET_MESSAGES_FOR_DEVICE_FLUX_NAME)
|
||||
.tap(Micrometer.metrics(Metrics.globalRegistry));
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> clear(UUID destinationUuid) {
|
||||
public CompletableFuture<Void> clear(final UUID destinationUuid) {
|
||||
if (experimentEnrollmentManager.isEnrolled(destinationUuid, MessagesManager.MIRROR_DELETIONS_EXPERIMENT_NAME)) {
|
||||
messageDeletionExecutor.execute(() -> {
|
||||
try {
|
||||
foundationDbMessageStore.clearAll(new AciServiceIdentifier(destinationUuid));
|
||||
} catch (final Exception e) {
|
||||
logger.warn("Failed to clear messages for {}", destinationUuid, e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return messagesCache.clear(destinationUuid);
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> clear(UUID destinationUuid, byte deviceId) {
|
||||
public CompletableFuture<Void> clear(final UUID destinationUuid, final byte deviceId) {
|
||||
if (experimentEnrollmentManager.isEnrolled(destinationUuid, MessagesManager.MIRROR_DELETIONS_EXPERIMENT_NAME)) {
|
||||
messageDeletionExecutor.execute(() -> {
|
||||
try {
|
||||
foundationDbMessageStore.clearAll(new AciServiceIdentifier(destinationUuid), deviceId);
|
||||
} catch (final Exception e) {
|
||||
logger.warn("Failed to clear messages for {}:{}", destinationUuid, deviceId, e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return messagesCache.clear(destinationUuid, deviceId);
|
||||
}
|
||||
|
||||
@@ -317,4 +397,29 @@ public class MessagesManager {
|
||||
final SealedSenderMultiRecipientMessage sealedSenderMultiRecipientMessage) {
|
||||
return messagesCache.insertSharedMultiRecipientMessagePayload(sealedSenderMultiRecipientMessage);
|
||||
}
|
||||
|
||||
/// Record versionstamps for the current time in the FoundationDB database(s).
|
||||
public void recordFoundationDbVersionstamps() {
|
||||
foundationDbMessageStore.recordVersionstamps();
|
||||
}
|
||||
|
||||
/// Clean up expired entries in the FoundationDB versionstamp clock.
|
||||
///
|
||||
/// @param oldestRetainedEntryTimestamp the earliest time for which we still want to be able to obtain a versionstamp
|
||||
public void expireOldFoundationDbVersionstamps(final Instant oldestRetainedEntryTimestamp) {
|
||||
foundationDbMessageStore.expireOldVersionstamps(oldestRetainedEntryTimestamp);
|
||||
}
|
||||
|
||||
/// Delete messages in FoundationDB for the given devices that were inserted before the given
|
||||
/// time. (Expiration of messages from Redis and Dynamo is handled automatically and do not
|
||||
/// require any interaction with this class.)
|
||||
///
|
||||
/// @param accountDeviceIdentifiers a map from ACI to the list of device IDs for which expired messages should be
|
||||
/// trimmed.
|
||||
///
|
||||
/// @param cutoffTime the expiration threshold. Messages inserted before this time may be deleted; messages inserted
|
||||
/// after it will not be.
|
||||
public void deleteFoundationDbMessagesBefore(final Map<AciServiceIdentifier, List<Byte>> accountDeviceIdentifiers, final Instant cutoffTime) {
|
||||
foundationDbMessageStore.deleteMessagesBefore(accountDeviceIdentifiers, cutoffTime);
|
||||
}
|
||||
}
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Flow;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStream;
|
||||
import reactor.adapter.JdkFlowAdapter;
|
||||
import reactor.core.Disposable;
|
||||
|
||||
/// A temporary message stream that can mirror message acknowledgements (deletion requests) to FoundationDB
|
||||
public class MirroringMessageStream implements MessageStream {
|
||||
|
||||
private final RedisDynamoDbMessageStream redisDynamoDbMessageStream;
|
||||
private final FoundationDbMessageStream foundationDbMessageStream;
|
||||
private final ExperimentEnrollmentManager experimentEnrollmentManager;
|
||||
|
||||
private final AciServiceIdentifier accountIdentifier;
|
||||
private final byte deviceId;
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(MirroringMessageStream.class);
|
||||
|
||||
public MirroringMessageStream(final RedisDynamoDbMessageStream redisDynamoDbMessageStream,
|
||||
final FoundationDbMessageStream foundationDbMessageStream,
|
||||
final ExperimentEnrollmentManager experimentEnrollmentManager,
|
||||
final UUID accountIdentifier,
|
||||
final byte deviceId) {
|
||||
|
||||
this.redisDynamoDbMessageStream = redisDynamoDbMessageStream;
|
||||
this.foundationDbMessageStream = foundationDbMessageStream;
|
||||
this.experimentEnrollmentManager = experimentEnrollmentManager;
|
||||
|
||||
this.accountIdentifier = new AciServiceIdentifier(accountIdentifier);
|
||||
this.deviceId = deviceId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Flow.Publisher<MessageStreamEntry> getMessages() {
|
||||
if (experimentEnrollmentManager.isEnrolled(accountIdentifier.uuid(), MessagesManager.MIRROR_READS_EXPERIMENT_NAME)) {
|
||||
final Disposable foundationDbDisposable =
|
||||
foundationDbMessageStream.getFiniteMessageStream()
|
||||
.limitRate(100)
|
||||
.subscribe();
|
||||
|
||||
return JdkFlowAdapter.publisherToFlowPublisher(
|
||||
JdkFlowAdapter.flowPublisherToFlux(redisDynamoDbMessageStream.getMessages())
|
||||
.doFinally(_ -> {
|
||||
try {
|
||||
foundationDbDisposable.dispose();
|
||||
} catch (final Exception _) {
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
return redisDynamoDbMessageStream.getMessages();
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Void> acknowledgeMessage(final UUID messageGuid, final long serverTimestamp) {
|
||||
// All messages stored in FoundationDB use version 8 UUIDs; if a message has a version 4 UUID, then it only exists
|
||||
// in Redis/DynamoDB
|
||||
if (messageGuid.version() == 8 &&
|
||||
experimentEnrollmentManager.isEnrolled(accountIdentifier.uuid(), MessagesManager.MIRROR_DELETIONS_EXPERIMENT_NAME)) {
|
||||
|
||||
foundationDbMessageStream.acknowledgeMessage(messageGuid, serverTimestamp)
|
||||
.whenComplete((_, throwable) -> {
|
||||
if (throwable != null) {
|
||||
logger.warn("Failed to delete message {}/{}/{} from FoundationDb", accountIdentifier.uuid(), deviceId,
|
||||
messageGuid, throwable);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return redisDynamoDbMessageStream.acknowledgeMessage(messageGuid, serverTimestamp);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import org.whispersystems.textsecuregcm.util.AttributeValues;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
|
||||
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.DeleteItemResponse;
|
||||
import software.amazon.awssdk.services.dynamodb.model.PutItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.PutItemResponse;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ReturnValue;
|
||||
import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.UpdateItemResponse;
|
||||
|
||||
public class ProfileAvatars {
|
||||
|
||||
private final DynamoDbClient dynamoDbClient;
|
||||
private final String tableName;
|
||||
private final Duration expiration;
|
||||
private final Clock clock;
|
||||
|
||||
// Identity that owns this profile; hash key; byte array
|
||||
@VisibleForTesting
|
||||
static final String KEY_IDENTITY = "I";
|
||||
|
||||
// URL of the avatar; string
|
||||
@VisibleForTesting
|
||||
static final String ATTR_URL = "U";
|
||||
|
||||
// Expiration timestamp, in seconds since the epoch, of the avatar; number
|
||||
@VisibleForTesting
|
||||
static final String ATTR_TTL = "E";
|
||||
|
||||
public ProfileAvatars(final DynamoDbClient dynamoDbClient, final String tableName, final Duration expiration, final
|
||||
Clock clock) {
|
||||
this.dynamoDbClient = dynamoDbClient;
|
||||
this.tableName = tableName;
|
||||
this.expiration = expiration;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
/// Sets the avatar URL for an identity
|
||||
///
|
||||
/// @return the previous URL, if any
|
||||
public Optional<String> setAvatarUrl(final byte[] identity, final String url) {
|
||||
final PutItemResponse response = dynamoDbClient.putItem(PutItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.item(Map.of(KEY_IDENTITY, AttributeValues.fromByteArray(identity),
|
||||
ATTR_URL, AttributeValues.fromString(url),
|
||||
ATTR_TTL, AttributeValues.fromLong(clock.instant().plus(expiration).getEpochSecond())))
|
||||
.returnValues(ReturnValue.ALL_OLD)
|
||||
.build());
|
||||
|
||||
return Optional.ofNullable(AttributeValues.getString(response.attributes(), ATTR_URL, null));
|
||||
}
|
||||
|
||||
/// @return the avatar URL, if present
|
||||
public Optional<String> updateAvatarTtl(final byte[] identity) {
|
||||
|
||||
final UpdateItemResponse response;
|
||||
try {
|
||||
response = dynamoDbClient.updateItem(UpdateItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.key(Map.of(KEY_IDENTITY, AttributeValues.fromByteArray(identity)))
|
||||
.conditionExpression("attribute_exists(#url)")
|
||||
.updateExpression("SET #ttl = :ttl")
|
||||
.expressionAttributeNames(Map.of(
|
||||
"#ttl", ATTR_TTL,
|
||||
"#url", ATTR_URL))
|
||||
.expressionAttributeValues(
|
||||
Map.of(":ttl", AttributeValues.fromLong(clock.instant().plus(expiration).getEpochSecond())))
|
||||
.returnValues(ReturnValue.ALL_OLD)
|
||||
.build());
|
||||
} catch (ConditionalCheckFailedException _) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
return Optional.ofNullable(AttributeValues.getString(response.attributes(), ATTR_URL, null));
|
||||
}
|
||||
|
||||
/// @return the deleted avatar URL, if present
|
||||
public Optional<String> deleteAvatarUrl(final byte[] identity) {
|
||||
final DeleteItemResponse response = dynamoDbClient.deleteItem(DeleteItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.key(Map.of(KEY_IDENTITY, AttributeValues.fromByteArray(identity)))
|
||||
.returnValues(ReturnValue.ALL_OLD)
|
||||
.build());
|
||||
|
||||
if (!response.hasAttributes()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
return Optional.ofNullable(response.attributes().get(ATTR_URL))
|
||||
.map(AttributeValue::s);
|
||||
}
|
||||
}
|
||||
+63
-9
@@ -14,7 +14,9 @@ import io.lettuce.core.RedisException;
|
||||
import io.lettuce.core.ScriptOutputType;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.io.IOException;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
@@ -29,9 +31,13 @@ import org.whispersystems.textsecuregcm.util.ResilienceUtil;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.util.retry.Retry;
|
||||
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem;
|
||||
import software.amazon.awssdk.services.s3.S3AsyncClient;
|
||||
import software.amazon.awssdk.services.s3.model.CopyObjectRequest;
|
||||
import software.amazon.awssdk.services.s3.model.DeleteObjectRequest;
|
||||
import software.amazon.awssdk.services.s3.model.MetadataDirective;
|
||||
import software.amazon.awssdk.services.s3.model.NoSuchKeyException;
|
||||
|
||||
public class ProfilesManager {
|
||||
|
||||
@@ -44,6 +50,7 @@ public class ProfilesManager {
|
||||
|
||||
private final Profiles profilesV1;
|
||||
private final ProfilesV2 profilesV2;
|
||||
private final ProfileAvatars profileAvatars;
|
||||
private final FaultTolerantRedisClusterClient cacheCluster;
|
||||
private final ScheduledExecutorService retryExecutor;
|
||||
private final S3AsyncClient s3Client;
|
||||
@@ -57,17 +64,19 @@ public class ProfilesManager {
|
||||
|
||||
public ProfilesManager(final Profiles profilesV1,
|
||||
final ProfilesV2 profilesV2,
|
||||
final ProfileAvatars profileAvatars,
|
||||
final FaultTolerantRedisClusterClient cacheCluster,
|
||||
final ScheduledExecutorService retryExecutor,
|
||||
final S3AsyncClient s3Client,
|
||||
final String bucket) throws IOException {
|
||||
this(profilesV1, profilesV2, cacheCluster, retryExecutor, s3Client, bucket,
|
||||
this(profilesV1, profilesV2, profileAvatars, cacheCluster, retryExecutor, s3Client, bucket,
|
||||
ClusterLuaScript.fromResource(cacheCluster, "lua/profile_set.lua", ScriptOutputType.STATUS));
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
ProfilesManager(final Profiles profilesV1,
|
||||
final ProfilesV2 profilesV2,
|
||||
final ProfileAvatars profileAvatars,
|
||||
final FaultTolerantRedisClusterClient cacheCluster,
|
||||
final ScheduledExecutorService retryExecutor,
|
||||
final S3AsyncClient s3Client,
|
||||
@@ -75,6 +84,7 @@ public class ProfilesManager {
|
||||
final ClusterLuaScript setLuaScript) {
|
||||
this.profilesV1 = profilesV1;
|
||||
this.profilesV2 = profilesV2;
|
||||
this.profileAvatars = profileAvatars;
|
||||
this.cacheCluster = cacheCluster;
|
||||
this.retryExecutor = retryExecutor;
|
||||
this.s3Client = s3Client;
|
||||
@@ -124,12 +134,10 @@ public class ProfilesManager {
|
||||
redisSet(uuid, versionedProfile, versionedProfileV1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete all profiles for the given uuid.
|
||||
* <p>
|
||||
* Avatars should be included for explicit delete actions, such as API calls and expired accounts. Implicit
|
||||
* deletions, such as registration, should preserve them, so that PIN recovery includes the avatar.
|
||||
*/
|
||||
/// Delete all profiles for the given uuid.
|
||||
///
|
||||
/// Avatars should be included for explicit delete actions, such as API calls and expired accounts. Implicit
|
||||
/// deletions, such as registration, should preserve them, so that PIN recovery includes the avatar.
|
||||
public CompletableFuture<Void> deleteAll(UUID uuid, final boolean includeAvatar) {
|
||||
|
||||
final CompletableFuture<Void> profilesV1AndAvatars = Mono.fromFuture(profilesV1.deleteAll(uuid))
|
||||
@@ -149,7 +157,7 @@ public class ProfilesManager {
|
||||
.bucket(bucket)
|
||||
.key(avatar)
|
||||
.build())
|
||||
.handle((ignored, throwable) -> {
|
||||
.whenComplete((_, throwable) -> {
|
||||
final String outcome;
|
||||
if (throwable != null) {
|
||||
logger.warn("Error deleting avatar", throwable);
|
||||
@@ -159,7 +167,6 @@ public class ProfilesManager {
|
||||
}
|
||||
|
||||
Metrics.counter(DELETE_AVATAR_COUNTER_NAME, "outcome", outcome).increment();
|
||||
return null;
|
||||
})
|
||||
.thenRun(Util.NOOP);
|
||||
}
|
||||
@@ -284,4 +291,51 @@ public class ProfilesManager {
|
||||
static byte[] getCacheKeyV1(UUID uuid) {
|
||||
return (CACHE_PREFIX_V1 + '{' + uuid.toString() + '}').getBytes();
|
||||
}
|
||||
|
||||
public void deleteAvatarForIdentity(final byte[] identity) {
|
||||
profileAvatars.deleteAvatarUrl(identity).ifPresent(avatar -> Mono.fromFuture(() ->
|
||||
deleteAvatar(avatar))
|
||||
.retry(3)
|
||||
.onErrorComplete()
|
||||
.block());
|
||||
}
|
||||
|
||||
/// Sets an avatar for the identity. If there was already an avatar, it will be deleted from storage.
|
||||
public void setAvatarForIdentity(byte[] identity, String avatar) {
|
||||
profileAvatars.setAvatarUrl(identity, avatar).map(previousAvatar -> Mono.fromFuture(() ->
|
||||
deleteAvatar(previousAvatar))
|
||||
.retry(3)
|
||||
.onErrorComplete()
|
||||
.block());
|
||||
}
|
||||
|
||||
public Optional<String> extendAvatarTtlForIdentity(final byte[] identity) {
|
||||
|
||||
final Optional<String> maybePath = profileAvatars.updateAvatarTtl(identity);
|
||||
|
||||
return maybePath.map(key -> {
|
||||
try {
|
||||
// copying the object to itself extends the expiration...
|
||||
Mono.fromFuture(() -> s3Client.copyObject(CopyObjectRequest.builder()
|
||||
.sourceBucket(bucket)
|
||||
.sourceKey(key)
|
||||
.destinationBucket(bucket)
|
||||
.destinationKey(key)
|
||||
.metadataDirective(MetadataDirective.REPLACE)
|
||||
// ...but there needs to be a trivial change, otherwise it is rejected
|
||||
.metadata(Map.of("t", String.valueOf(Instant.now().getEpochSecond())))
|
||||
.build()))
|
||||
.retryWhen(Retry.max(3).filter(e -> !(e instanceof NoSuchKeyException)))
|
||||
.block();
|
||||
|
||||
return key;
|
||||
} catch (NoSuchKeyException _) {
|
||||
logger.warn("avatar expected to be present is gone");
|
||||
|
||||
profileAvatars.deleteAvatarUrl(identity);
|
||||
|
||||
return null;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
+25
-2
@@ -9,10 +9,14 @@ import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Flow;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
import reactor.adapter.JdkFlowAdapter;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
/// A [MessageStream] implementation that produces message from a joint DynamoDB/Redis message store.
|
||||
public class RedisDynamoDbMessageStream implements MessageStream {
|
||||
@@ -25,6 +29,14 @@ public class RedisDynamoDbMessageStream implements MessageStream {
|
||||
|
||||
private final RedisDynamoDbMessagePublisher messagePublisher;
|
||||
|
||||
private static final String MESSAGE_READ_COUNTER_NAME =
|
||||
name(RedisDynamoDbMessageStream.class, "messagesRead");
|
||||
|
||||
private static final String MESSAGE_ACKNOWLEDGED_COUNTER_NAME =
|
||||
name(RedisDynamoDbMessageStream.class, "messagesAcknowledged");
|
||||
|
||||
private static final String UUID_VERSION_TAG = "uuidVersion";
|
||||
|
||||
public RedisDynamoDbMessageStream(final MessagesDynamoDb messagesDynamoDb,
|
||||
final MessagesCache messagesCache,
|
||||
final RedisMessageAvailabilityManager redisMessageAvailabilityManager,
|
||||
@@ -54,11 +66,22 @@ public class RedisDynamoDbMessageStream implements MessageStream {
|
||||
|
||||
@Override
|
||||
public Flow.Publisher<MessageStreamEntry> getMessages() {
|
||||
return messagePublisher;
|
||||
return JdkFlowAdapter.publisherToFlowPublisher(JdkFlowAdapter.flowPublisherToFlux(messagePublisher)
|
||||
.doOnNext(messageStreamEntry -> {
|
||||
if (messageStreamEntry instanceof MessageStreamEntry.Envelope(org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope message)) {
|
||||
final UUID messageGuid = UUIDUtil.fromByteString(message.getServerGuid());
|
||||
|
||||
Metrics.counter(MESSAGE_READ_COUNTER_NAME, UUID_VERSION_TAG, String.valueOf(messageGuid.version()))
|
||||
.increment();
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Void> acknowledgeMessage(final UUID messageGuid, final long serverTimestamp) {
|
||||
Metrics.counter(MESSAGE_ACKNOWLEDGED_COUNTER_NAME, UUID_VERSION_TAG, String.valueOf(messageGuid.version()))
|
||||
.increment();
|
||||
|
||||
return messagesCache.remove(accountIdentifier, device.getId(), messageGuid)
|
||||
.thenCompose(removed -> removed.map(_ -> CompletableFuture.<Void>completedFuture(null))
|
||||
.orElseGet(() ->
|
||||
|
||||
+14
-8
@@ -26,17 +26,23 @@ public record SubscriberCredentials(@Nonnull byte[] subscriberBytes,
|
||||
@Nonnull Instant now) {
|
||||
|
||||
public static SubscriberCredentials process(
|
||||
Optional<AuthenticatedDevice> authenticatedAccount,
|
||||
String subscriberId,
|
||||
Clock clock) throws SubscriptionException {
|
||||
Instant now = clock.instant();
|
||||
final Optional<AuthenticatedDevice> authenticatedAccount,
|
||||
final String subscriberId,
|
||||
final Clock clock) throws SubscriptionException {
|
||||
if (authenticatedAccount.isPresent()) {
|
||||
throw new SubscriptionForbiddenException("must not use authenticated connection for subscriber operations");
|
||||
}
|
||||
byte[] subscriberBytes = convertSubscriberIdStringToBytes(subscriberId);
|
||||
byte[] subscriberUser = getUser(subscriberBytes);
|
||||
byte[] subscriberKey = getKey(subscriberBytes);
|
||||
byte[] hmac = computeHmac(subscriberUser, subscriberKey);
|
||||
final byte[] subscriberBytes = convertSubscriberIdStringToBytes(subscriberId);
|
||||
return process(subscriberBytes, clock);
|
||||
}
|
||||
|
||||
public static SubscriberCredentials process(
|
||||
final byte[] subscriberBytes,
|
||||
final Clock clock) {
|
||||
final Instant now = clock.instant();
|
||||
final byte[] subscriberUser = getUser(subscriberBytes);
|
||||
final byte[] subscriberKey = getKey(subscriberBytes);
|
||||
final byte[] hmac = computeHmac(subscriberUser, subscriberKey);
|
||||
return new SubscriberCredentials(subscriberBytes, subscriberUser, subscriberKey, hmac, now);
|
||||
}
|
||||
|
||||
|
||||
+32
-21
@@ -12,7 +12,6 @@ import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import java.util.function.BiFunction;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
@@ -23,24 +22,26 @@ 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;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.GooglePlayBillingManager;
|
||||
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.subscriptions.SubscriberIdCreationNotPermittedException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionForbiddenException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInformation;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidArgumentsException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidIdempotencyKeyException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidLevelException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionNotFoundException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentProcessor;
|
||||
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.SubscriptionReceiptAlreadyRedeemedException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptRequestedForOpenPaymentException;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.util.ThrowingBiFunction;
|
||||
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
|
||||
|
||||
/**
|
||||
@@ -103,16 +104,23 @@ public class SubscriptionManager {
|
||||
* already exists, its last access time will be updated.
|
||||
*
|
||||
* @param subscriberCredentials Subscriber credentials derived from the subscriberId
|
||||
* @param createPermitted Whether creating a new subscriber is permitted if one does not exist
|
||||
* @throws SubscriptionForbiddenException if the subscriber credentials were incorrect
|
||||
* @throws SubscriberIdCreationNotPermittedException if a new subscriber ID would be created, but the caller does not permit it
|
||||
*/
|
||||
public void updateSubscriber(final SubscriberCredentials subscriberCredentials)
|
||||
throws SubscriptionForbiddenException {
|
||||
public void updateSubscriber(final SubscriberCredentials subscriberCredentials, final boolean createPermitted)
|
||||
throws SubscriptionForbiddenException, SubscriberIdCreationNotPermittedException {
|
||||
final Subscriptions.GetResult getResult =
|
||||
subscriptions.get(subscriberCredentials.subscriberUser(), subscriberCredentials.hmac());
|
||||
|
||||
if (getResult == Subscriptions.GetResult.PASSWORD_MISMATCH) {
|
||||
throw new SubscriptionForbiddenException("subscriberId mismatch");
|
||||
} else if (getResult == Subscriptions.GetResult.NOT_STORED) {
|
||||
|
||||
if (!createPermitted) {
|
||||
throw new SubscriberIdCreationNotPermittedException();
|
||||
}
|
||||
|
||||
// create a customer and write it to ddb
|
||||
final Subscriptions.Record updatedRecord = subscriptions.create(subscriberCredentials.subscriberUser(),
|
||||
subscriberCredentials.hmac(),
|
||||
@@ -165,10 +173,11 @@ public class SubscriptionManager {
|
||||
/**
|
||||
* Create a ZK receipt credential for a subscription that can be used to obtain the user entitlement
|
||||
*
|
||||
* @param subscriberCredentials Subscriber credentials derived from the subscriberId
|
||||
* @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
|
||||
* @param subscriberCredentials Subscriber credentials derived from the subscriberId
|
||||
* @param receiptCredentialRequestBytes The raw bytes of the ZK Receipt credential request
|
||||
* @param expiration A function that takes a
|
||||
* {@link CustomerAwareSubscriptionPaymentProcessor.ReceiptItem} and returns the
|
||||
* expiration time of the receipt
|
||||
* @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
|
||||
@@ -178,12 +187,13 @@ public class SubscriptionManager {
|
||||
* user an entitlement
|
||||
* @throws SubscriptionReceiptRequestedForOpenPaymentException if a receipt was requested while a payment transaction
|
||||
* was still open
|
||||
* @throws SubscriptionReceiptAlreadyRedeemedException if the receipt was already redeemed by a different request
|
||||
* @throws SubscriptionReceiptAlreadyRedeemedException if the receipt was already redeemed by a different
|
||||
* request
|
||||
* @throws RateLimitExceededException if rate-limited
|
||||
*/
|
||||
public ReceiptResult createReceiptCredentials(
|
||||
final SubscriberCredentials subscriberCredentials,
|
||||
final SubscriptionController.GetReceiptCredentialsRequest request,
|
||||
final byte[] receiptCredentialRequestBytes,
|
||||
final Function<CustomerAwareSubscriptionPaymentProcessor.ReceiptItem, Instant> expiration)
|
||||
throws SubscriptionForbiddenException, SubscriptionNotFoundException, SubscriptionInvalidArgumentsException, SubscriptionPaymentRequiredException, RateLimitExceededException, SubscriptionReceiptRequestedForOpenPaymentException, SubscriptionReceiptAlreadyRedeemedException {
|
||||
final Subscriptions.Record record = getSubscriber(subscriberCredentials);
|
||||
@@ -193,7 +203,7 @@ public class SubscriptionManager {
|
||||
|
||||
final ReceiptCredentialRequest receiptCredentialRequest;
|
||||
try {
|
||||
receiptCredentialRequest = new ReceiptCredentialRequest(request.receiptCredentialRequest());
|
||||
receiptCredentialRequest = new ReceiptCredentialRequest(receiptCredentialRequestBytes);
|
||||
} catch (final InvalidInputException e) {
|
||||
throw new SubscriptionInvalidArgumentsException("invalid receipt credential request", e);
|
||||
}
|
||||
@@ -235,19 +245,20 @@ 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
|
||||
* @param <E> An exception thrown by the paymentSetupFunction
|
||||
* @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
|
||||
* @throws SubscriptionProcessorConflictException if the new payment processor does not match the existing processor associated with
|
||||
* the subscriberId
|
||||
*/
|
||||
public <T extends CustomerAwareSubscriptionPaymentProcessor, R> R addPaymentMethodToCustomer(
|
||||
public <T extends CustomerAwareSubscriptionPaymentProcessor, R, E extends Exception> R addPaymentMethodToCustomer(
|
||||
final SubscriberCredentials subscriberCredentials,
|
||||
final T subscriptionPaymentProcessor,
|
||||
final ClientPlatform clientPlatform,
|
||||
final BiFunction<T, String, R> paymentSetupFunction)
|
||||
throws SubscriptionForbiddenException, SubscriptionNotFoundException, SubscriptionProcessorConflictException {
|
||||
final ThrowingBiFunction<T, String, R, E> paymentSetupFunction)
|
||||
throws SubscriptionForbiddenException, SubscriptionNotFoundException, SubscriptionProcessorConflictException, E {
|
||||
|
||||
Subscriptions.Record record = this.getSubscriber(subscriberCredentials);
|
||||
if (record.getProcessorCustomer().isEmpty()) {
|
||||
@@ -313,7 +324,7 @@ public class SubscriptionManager {
|
||||
final String idempotencyKey,
|
||||
final String subscriptionTemplateId,
|
||||
final LevelTransitionValidator transitionValidator)
|
||||
throws SubscriptionInvalidArgumentsException, SubscriptionProcessorConflictException, SubscriptionProcessorException {
|
||||
throws SubscriptionInvalidLevelException, SubscriptionInvalidIdempotencyKeyException, SubscriptionPaymentRequiresActionException, SubscriptionProcessorConflictException, SubscriptionProcessorException {
|
||||
|
||||
if (record.subscriptionId != null) {
|
||||
// we already have a subscription in our records so let's check the level and currency,
|
||||
@@ -364,7 +375,7 @@ public class SubscriptionManager {
|
||||
* @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
|
||||
* @throws SubscriptionProcessorConflictException if the new payment processor does not match the existing processor associated with
|
||||
* the subscriberId
|
||||
* @throws SubscriptionPaymentRequiredException if the subscription is not in a state that grants the user an
|
||||
* entitlement
|
||||
@@ -416,7 +427,7 @@ public class SubscriptionManager {
|
||||
* @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
|
||||
* @throws SubscriptionProcessorConflictException if the new payment processor does not match the existing processor associated with
|
||||
* the subscriber
|
||||
* @throws SubscriptionInvalidArgumentsException if the originalTransactionId is malformed or does not represent a
|
||||
* valid subscription
|
||||
|
||||
-113
@@ -1,113 +0,0 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage.foundationdb;
|
||||
|
||||
import com.apple.foundationdb.tuple.Versionstamp;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.NavigableMap;
|
||||
import java.util.TreeMap;
|
||||
|
||||
/// An acknowledged message buffer keeps track of messages that have been sent, whether they have been acknowledged by
|
||||
/// the recipient, and whether those acknowledgements have been flushed to the underlying data store. It also batches
|
||||
/// acknowledgements into contiguous ranges in the interest of efficiency.
|
||||
class AcknowledgedMessageBuffer {
|
||||
|
||||
/// The maximum number of unacknowledged messages we will send before closing the stream with an error
|
||||
private final int maxUnacknowledgedMessages;
|
||||
|
||||
/// Map of versionstamp -> acknowledged? to keep track of acknowledged versionstamp ranges to clear
|
||||
private final NavigableMap<Versionstamp, Boolean> sentVersionstamps = new TreeMap<>();
|
||||
private int unacknowledgedMessages = 0;
|
||||
|
||||
AcknowledgedMessageBuffer(final int maxUnacknowledgedMessages) {
|
||||
this.maxUnacknowledgedMessages = maxUnacknowledgedMessages;
|
||||
}
|
||||
|
||||
public synchronized void addUnacknowledgedMessage(final Versionstamp versionstamp) throws TooManyUnacknowledgedMessagesException {
|
||||
if (++unacknowledgedMessages > maxUnacknowledgedMessages) {
|
||||
throw new TooManyUnacknowledgedMessagesException();
|
||||
}
|
||||
|
||||
sentVersionstamps.put(versionstamp, false);
|
||||
}
|
||||
|
||||
public synchronized void acknowledgeMessage(final Versionstamp versionstamp) {
|
||||
// If we don't know about this versionstamp, or it's already acknowledged, there's nothing to do
|
||||
if (!sentVersionstamps.containsKey(versionstamp) || sentVersionstamps.get(versionstamp)) {
|
||||
return;
|
||||
}
|
||||
|
||||
unacknowledgedMessages--;
|
||||
sentVersionstamps.put(versionstamp, true);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
int getUnacknowledgedMessageCount() {
|
||||
return unacknowledgedMessages;
|
||||
}
|
||||
|
||||
/// Computes a list of acknowledged contiguous versionstamp ranges that can be cleared from the database and removes
|
||||
/// them from ths unacknowledged mesage buffer.
|
||||
///
|
||||
/// @return a list of acknowledged contiguous versionstamp ranges that can be cleared from the database.
|
||||
public synchronized List<Pair<Versionstamp, Versionstamp>> takeFlushableRanges() {
|
||||
final List<Pair<Versionstamp, Versionstamp>> flushableRanges = computeFlushableRanges();
|
||||
flushableRanges.forEach(range -> sentVersionstamps.subMap(range.first(), true, range.second(), true).clear());
|
||||
|
||||
return flushableRanges;
|
||||
}
|
||||
|
||||
/// Computes a list of acknowledged contiguous versionstamp ranges that can be cleared from the database.
|
||||
///
|
||||
/// @return a list of acknowledged contiguous versionstamp ranges that can be cleared from the database.
|
||||
@VisibleForTesting
|
||||
synchronized List<Pair<Versionstamp, Versionstamp>> computeFlushableRanges() {
|
||||
final List<Pair<Versionstamp, Versionstamp>> flushableRanges = new ArrayList<>();
|
||||
Versionstamp startInclusive = null;
|
||||
Versionstamp endInclusive = null;
|
||||
|
||||
for (final Map.Entry<Versionstamp, Boolean> entry : sentVersionstamps.entrySet()) {
|
||||
if (entry.getValue()) {
|
||||
// Message is acknowledged, so we can either start tracking a new range if we aren't already, or extend our
|
||||
// current range
|
||||
if (startInclusive == null) {
|
||||
startInclusive = entry.getKey();
|
||||
}
|
||||
endInclusive = entry.getKey();
|
||||
} else {
|
||||
// Message is un-acknowledged, which means either it is a "range-breaker" or we never started tracking an
|
||||
// acknowledged range. Mark the currently tracked range flushable, if it exists.
|
||||
if (startInclusive != null) {
|
||||
assert endInclusive != null;
|
||||
flushableRanges.add(new Pair<>(startInclusive, endInclusive));
|
||||
startInclusive = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (startInclusive != null) {
|
||||
assert endInclusive != null;
|
||||
flushableRanges.add(new Pair<>(startInclusive, endInclusive));
|
||||
}
|
||||
|
||||
return flushableRanges;
|
||||
}
|
||||
|
||||
|
||||
/// Acknowledges a stale ephemeral message for cleanup from FoundationDB.
|
||||
/// Ephemeral messages are only delivered when the recipient has an active message stream, so any ephemeral message
|
||||
/// read from the finite publisher is stale by definition and can be immediately acknowledged and discarded.
|
||||
///
|
||||
/// @param versionstamp The versionstamp to acknowledge
|
||||
public synchronized void acknowledgeStaleEphemeralMessage(final Versionstamp versionstamp) {
|
||||
sentVersionstamps.put(versionstamp, true);
|
||||
}
|
||||
|
||||
}
|
||||
+217
-110
@@ -5,36 +5,82 @@ import com.apple.foundationdb.KeySelector;
|
||||
import com.apple.foundationdb.StreamingMode;
|
||||
import com.apple.foundationdb.Transaction;
|
||||
import com.apple.foundationdb.tuple.Versionstamp;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.protobuf.InvalidProtocolBufferException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.time.Clock;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ScheduledFuture;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import java.util.function.BiConsumer;
|
||||
import javax.annotation.Nullable;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.FluxSink;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Supplier;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
/// Publishes a message stream from a device queue in FoundationDB. Capable of publishing both a finite stream for
|
||||
/// catching up to end-of-queue,and an infinite stream for live updates.
|
||||
class FoundationDbMessagePublisher {
|
||||
|
||||
private final Database database;
|
||||
/// The maximum number of messages we will fetch per range query operation to avoid excessive memory consumption
|
||||
private final int maxMessagesPerScan;
|
||||
private final Clock clock;
|
||||
/// Keeps track of the key from which to start reading on the next iteration
|
||||
private volatile KeySelector beginKeyCursor;
|
||||
/// The end key at which we stop reading messages. For finite publisher, this is just past the end-of-queue key at the
|
||||
/// time the publisher was created. For an infinite publisher, this is the end of subspace range.
|
||||
private final KeySelector endKeyExclusive;
|
||||
|
||||
/// Keeps track of the key from which to start reading on the next iteration
|
||||
private volatile KeySelector beginKeyCursor;
|
||||
/// The maximum number of messages we will fetch per range query operation to avoid excessive memory consumption
|
||||
private final int maxMessagesPerScan;
|
||||
|
||||
/// The key that stores the server ID/timestamp indicating when/where the connected client was last known to be
|
||||
/// present. Active publishers refresh this key at regular intervals (see [#renewPresenceFuture]).
|
||||
@Nullable private final byte[] presenceKey;
|
||||
|
||||
// An ID for this specific stream for use when checking "ownership" of a presence value.
|
||||
private final int streamId = NEXT_STREAM_ID.getAndIncrement();
|
||||
|
||||
/// The key that is updated whenever new messages are available in the queue. If null, it is inferred that the publisher
|
||||
/// is finite and will terminate when the end-of-queue at time of publisher creation is reached. Otherwise, the publisher
|
||||
/// is "infinite" and will continue to wait for new messages and publish them in a loop.
|
||||
@Nullable private final byte[] messagesAvailableWatchKey;
|
||||
|
||||
/// Listener to watch for state machine transitions; used for testing.
|
||||
private final BiConsumer<State, State> stateChangeListener;
|
||||
|
||||
/// Whether the publisher is finite or infinite.
|
||||
private final boolean terminateOnQueueEmpty;
|
||||
|
||||
/// Tracks the current state of the publisher state machine. Initial state presumes that messages are available in the queue.
|
||||
private State state = State.MESSAGES_AVAILABLE;
|
||||
|
||||
private final Flux<FoundationDbMessageStreamEntry.Message> messagePublisher;
|
||||
|
||||
/// Reference to the sink we publish messages to.
|
||||
private volatile FluxSink<FoundationDbMessageStreamEntry.Message> emitter;
|
||||
|
||||
/// Future that completes when the watch for {@link #messagesAvailableWatchKey} triggers.
|
||||
private CompletableFuture<Void> watchFuture;
|
||||
|
||||
/// A future for refreshing the connected client's presence value at regular intervals.
|
||||
@Nullable private ScheduledFuture<?> renewPresenceFuture;
|
||||
|
||||
private final AtomicLong totalRequested = new AtomicLong(0);
|
||||
private final AtomicLong totalEmitted = new AtomicLong(0);
|
||||
|
||||
private static final AtomicInteger NEXT_STREAM_ID = new AtomicInteger();
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(FoundationDbMessagePublisher.class);
|
||||
|
||||
enum State {
|
||||
/// Messages are likely available in the queue. Initial state.
|
||||
@@ -70,50 +116,57 @@ class FoundationDbMessagePublisher {
|
||||
FETCH_OR_PUBLISH_ERROR_OCCURRED
|
||||
}
|
||||
|
||||
/// The key that is updated whenever new messages are available in the queue. If null, it is inferred that the publisher
|
||||
/// is finite and will terminate when the end-of-queue at time of publisher creation is reached. Otherwise, the publisher
|
||||
/// is "infinite" and will continue to wait for new messages and publish them in a loop.
|
||||
@Nullable private final byte[] messagesAvailableWatchKey;
|
||||
/// Listener to watch for state machine transitions; used for testing.
|
||||
private final BiConsumer<State, State> stateChangeListener;
|
||||
private final Flux<FoundationDbMessageStreamEntry.Message> messagePublisher;
|
||||
/// Whether the publisher is finite or infinite.
|
||||
private final boolean terminateOnQueueEmpty;
|
||||
/// A supplier that returns a function to execute before we begin fetching a page; it is passed the transaction that
|
||||
/// is started for the page fetch operations.
|
||||
private final Supplier<Consumer<Transaction>> beforePageFetch;
|
||||
|
||||
/// Tracks the current state of the publisher state machine. Initial state presumes that messages are available in the queue.
|
||||
private State state = State.MESSAGES_AVAILABLE;
|
||||
/// Reference to the sink we publishes messages to.
|
||||
private volatile FluxSink<FoundationDbMessageStreamEntry.Message> emitter;
|
||||
/// Future that completes when the watch for {@link #messagesAvailableWatchKey} triggers.
|
||||
private CompletableFuture<Void> watchFuture;
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(FoundationDbMessagePublisher.class);
|
||||
|
||||
FoundationDbMessagePublisher(
|
||||
final Database database,
|
||||
final Clock clock,
|
||||
final KeySelector beginKeyInclusive,
|
||||
final KeySelector endKeyExclusive,
|
||||
final Database database,
|
||||
final int maxMessagesPerScan,
|
||||
@Nullable final byte[] presenceKey,
|
||||
@Nullable final ScheduledExecutorService presenceRenewalExecutorService,
|
||||
@Nullable final byte[] messagesAvailableWatchKey,
|
||||
@Nullable final BiConsumer<State, State> stateChangeListener,
|
||||
final Supplier<Consumer<Transaction>> beforePageFetch) {
|
||||
@Nullable final BiConsumer<State, State> stateChangeListener) {
|
||||
|
||||
this.database = database;
|
||||
this.clock = clock;
|
||||
this.beginKeyCursor = beginKeyInclusive;
|
||||
this.endKeyExclusive = endKeyExclusive;
|
||||
this.database = database;
|
||||
this.maxMessagesPerScan = maxMessagesPerScan;
|
||||
this.presenceKey = presenceKey;
|
||||
this.messagesAvailableWatchKey = messagesAvailableWatchKey;
|
||||
this.terminateOnQueueEmpty = messagesAvailableWatchKey == null;
|
||||
this.stateChangeListener = stateChangeListener != null ? stateChangeListener : (_, _) -> {};
|
||||
this.beforePageFetch = beforePageFetch;
|
||||
this.messagePublisher = Flux.create(emitter -> {
|
||||
this.emitter = emitter;
|
||||
emitter.onRequest(_ -> transitionStateOnEvent(Event.DEMAND_REQUESTED));
|
||||
emitter.onDispose(this::onDispose);
|
||||
});
|
||||
|
||||
if (!terminateOnQueueEmpty) {
|
||||
Objects.requireNonNull(presenceKey);
|
||||
Objects.requireNonNull(presenceRenewalExecutorService);
|
||||
}
|
||||
|
||||
this.messagePublisher = Mono.fromFuture(() -> {
|
||||
if (!terminateOnQueueEmpty) {
|
||||
// Establish presence before attempting to fetch messages. We must establish presence for watches to work as
|
||||
// expected. If we fail to establish presence, then this non-terminating stream will never learn about new
|
||||
// messages. If establishing presence throws an exception, then the whole publisher will terminate with that
|
||||
// exception.
|
||||
return database.runAsync(transaction -> {
|
||||
setPresence(transaction);
|
||||
return CompletableFuture.completedFuture(null);
|
||||
})
|
||||
.thenRun(() -> startPresenceRenewal(presenceRenewalExecutorService));
|
||||
} else {
|
||||
return CompletableFuture.completedFuture(null);
|
||||
}
|
||||
})
|
||||
.thenMany(Flux.create(emitter -> {
|
||||
this.emitter = emitter;
|
||||
emitter.onRequest(n -> {
|
||||
final long totalRequestedCount = totalRequested.addAndGet(n);
|
||||
if (totalRequestedCount > totalEmitted.get()) {
|
||||
transitionStateOnEvent(Event.DEMAND_REQUESTED);
|
||||
}
|
||||
});
|
||||
emitter.onDispose(this::onDispose);
|
||||
}));
|
||||
}
|
||||
|
||||
/// Creates a [FoundationDbMessagePublisher] that publishes a stream of messages in a queue that terminates when it
|
||||
@@ -121,39 +174,45 @@ class FoundationDbMessagePublisher {
|
||||
/// cases when callers need to "catch up" on stored messages without following fresh updates (for example, when a
|
||||
/// client first connects and needs to load stored messages before receiving a "live" stream of new messages).
|
||||
public static FoundationDbMessagePublisher createFinitePublisher(
|
||||
final Database database,
|
||||
final Clock clock,
|
||||
final KeySelector beginKeyInclusive,
|
||||
final KeySelector endKeyExclusive,
|
||||
final Database database,
|
||||
final int maxMessagesPerScan,
|
||||
final Supplier<Consumer<Transaction>> beforePageFetch) {
|
||||
final int maxMessagesPerScan) {
|
||||
|
||||
return new FoundationDbMessagePublisher(beginKeyInclusive,
|
||||
return new FoundationDbMessagePublisher(database,
|
||||
clock,
|
||||
beginKeyInclusive,
|
||||
endKeyExclusive,
|
||||
database,
|
||||
maxMessagesPerScan,
|
||||
null,
|
||||
null,
|
||||
beforePageFetch);
|
||||
null,
|
||||
null);
|
||||
}
|
||||
|
||||
/// Creates a [FoundationDbMessagePublisher] that publishes a non-terminating stream of messages from a device queue.
|
||||
/// It waits for new messages and publishes them in a loop. Useful when a client has finished receiving its stored
|
||||
/// messages and is now waiting for a live stream of new messages.
|
||||
public static FoundationDbMessagePublisher createInfinitePublisher(
|
||||
final Database database,
|
||||
final Clock clock,
|
||||
final KeySelector beginKeyInclusive,
|
||||
final KeySelector endKeyExclusive,
|
||||
final Database database,
|
||||
final int maxMessagesPerScan,
|
||||
final byte[] messagesAvailableWatchKey,
|
||||
final Supplier<Consumer<Transaction>> beforePageFetch) {
|
||||
final byte[] presenceKey,
|
||||
final ScheduledExecutorService presenceRenewalExecutorService,
|
||||
final byte[] messagesAvailableWatchKey) {
|
||||
|
||||
return new FoundationDbMessagePublisher(beginKeyInclusive,
|
||||
return new FoundationDbMessagePublisher(database,
|
||||
clock,
|
||||
beginKeyInclusive,
|
||||
endKeyExclusive,
|
||||
database,
|
||||
maxMessagesPerScan,
|
||||
presenceKey,
|
||||
presenceRenewalExecutorService,
|
||||
messagesAvailableWatchKey,
|
||||
null,
|
||||
beforePageFetch);
|
||||
null);
|
||||
}
|
||||
|
||||
private synchronized void setState(final State newState, final Event event) {
|
||||
@@ -192,6 +251,7 @@ class FoundationDbMessagePublisher {
|
||||
setState(State.MESSAGES_AVAILABLE, event);
|
||||
transitionStateOnEvent(Event.INTERNAL_TRIGGER);
|
||||
}
|
||||
case MESSAGE_AVAILABLE_WATCH_TRIGGERED -> setState(State.MESSAGE_AVAILABLE_SIGNAL_BUFFERED, event);
|
||||
case FETCH_OR_PUBLISH_ERROR_OCCURRED -> setState(State.ERROR, event);
|
||||
default -> knownTransition = false;
|
||||
}
|
||||
@@ -241,64 +301,43 @@ class FoundationDbMessagePublisher {
|
||||
|
||||
/// Fetch messages using a range query limiting batch size to [#maxMessagesPerScan]. If the query returns fewer than
|
||||
/// [#maxMessagesPerScan], emit [Event#FETCHED_ALL_AVAILABLE_MESSAGES]. In the case of an infinite publisher, also set
|
||||
/// a watch for new messages. Execute the function supplied by [#beforePageFetch] in the context of the transaction.
|
||||
/// Additionally, the cursor is updated so that we begin fetching from the right key on
|
||||
/// subsequent scans
|
||||
/// a watch for new messages. Additionally, the cursor is updated so that we begin fetching from the right key on
|
||||
/// subsequent scans.
|
||||
///
|
||||
/// @return a future of a list of [FoundationDbMessageStreamEntry.Message] with a max size of [#maxMessagesPerScan]
|
||||
private CompletableFuture<List<FoundationDbMessageStreamEntry.Message>> getMessagesBatch() {
|
||||
final Consumer<Transaction> doBeforePageFetch = beforePageFetch.get();
|
||||
return database.runAsync(transaction -> {
|
||||
doBeforePageFetch.accept(transaction);
|
||||
return getItemsInRange(transaction, beginKeyCursor, endKeyExclusive, maxMessagesPerScan)
|
||||
.thenApply(lastKeyReadAndItems -> {
|
||||
// Set our beginning key to just past the last key read so that we're ready for our next fetch
|
||||
lastKeyReadAndItems.first()
|
||||
.ifPresent(lastKeyRead -> beginKeyCursor = KeySelector.firstGreaterThan(lastKeyRead));
|
||||
|
||||
final List<FoundationDbMessageStreamEntry.Message> items = lastKeyReadAndItems.second();
|
||||
if (items.size() < maxMessagesPerScan) {
|
||||
transitionStateOnEvent(Event.FETCHED_ALL_AVAILABLE_MESSAGES);
|
||||
if (!terminateOnQueueEmpty) {
|
||||
return database.runAsync(transaction ->
|
||||
transaction.getRange(beginKeyCursor, endKeyExclusive, maxMessagesPerScan, false, StreamingMode.EXACT).asList()
|
||||
.thenApply(keyValues -> {
|
||||
if (keyValues.size() < maxMessagesPerScan && !terminateOnQueueEmpty) {
|
||||
setWatch(transaction);
|
||||
}
|
||||
}
|
||||
return items;
|
||||
});
|
||||
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/// Fetch messages in the range between `begin` and `end` limited to a batch size of `maxMessagesPerSccan`
|
||||
///
|
||||
/// @param transaction the FoundationDB transaction in which to perform the read query
|
||||
/// @param beginInclusive the range start key (inclusive)
|
||||
/// @param endExclusive the range end key (exclusive)
|
||||
/// @param maxMessagesPerScan maximum number of messages to return in the fetch query
|
||||
/// @return the last key read (if there were non-zero number of messages read) and the list of messages read
|
||||
private CompletableFuture<Pair<Optional<byte[]>, List<FoundationDbMessageStreamEntry.Message>>> getItemsInRange(
|
||||
final Transaction transaction,
|
||||
final KeySelector beginInclusive,
|
||||
final KeySelector endExclusive,
|
||||
final int maxMessagesPerScan) {
|
||||
return transaction.getRange(beginInclusive, endExclusive, maxMessagesPerScan, false, StreamingMode.EXACT).asList()
|
||||
return keyValues;
|
||||
}))
|
||||
.thenApply(keyValues -> {
|
||||
final Optional<byte[]> lastKeyRead = keyValues.isEmpty()
|
||||
? Optional.empty()
|
||||
: Optional.of(keyValues.getLast().getKey());
|
||||
final List<FoundationDbMessageStreamEntry.Message> messages = keyValues.stream()
|
||||
if (keyValues.size() < maxMessagesPerScan) {
|
||||
transitionStateOnEvent(Event.FETCHED_ALL_AVAILABLE_MESSAGES);
|
||||
}
|
||||
|
||||
if (keyValues.isEmpty()) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
beginKeyCursor = KeySelector.firstGreaterThan(keyValues.getLast().getKey());
|
||||
|
||||
return keyValues.stream()
|
||||
.map(keyValue -> {
|
||||
final Versionstamp versionstamp = FoundationDbMessageStore.getVersionstamp(keyValue.getKey());
|
||||
|
||||
try {
|
||||
return new FoundationDbMessageStreamEntry.Message(versionstamp, MessageProtos.Envelope.parseFrom(keyValue.getValue()));
|
||||
return new FoundationDbMessageStreamEntry.Message(versionstamp,
|
||||
MessageProtos.Envelope.parseFrom(keyValue.getValue()));
|
||||
} catch (final InvalidProtocolBufferException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
})
|
||||
.toList();
|
||||
return new Pair<>(lastKeyRead, messages);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -313,6 +352,7 @@ class FoundationDbMessagePublisher {
|
||||
getMessagesBatch()
|
||||
.thenAccept(messageStreamEntries -> {
|
||||
messageStreamEntries.forEach(emitter::next);
|
||||
totalEmitted.addAndGet(messageStreamEntries.size());
|
||||
transitionStateOnEvent(Event.PUBLISHED_MESSAGES);
|
||||
})
|
||||
.exceptionally(t -> {
|
||||
@@ -338,15 +378,6 @@ class FoundationDbMessagePublisher {
|
||||
watchFuture.thenRun(() -> transitionStateOnEvent(Event.MESSAGE_AVAILABLE_WATCH_TRIGGERED));
|
||||
}
|
||||
|
||||
private synchronized void onDispose() {
|
||||
// Unless the state machine is an already terminal state, directly set state to "terminated", since there's no point
|
||||
// in evaluating the state machine when there's no live subscription.
|
||||
if (state != State.TERMINATED && state != State.ERROR) {
|
||||
setState(State.TERMINATED, Event.INTERNAL_TRIGGER);
|
||||
}
|
||||
cancelWatch();
|
||||
}
|
||||
|
||||
/// Cancel the watch (if any). Although inactive watches are automatically timed-out, we explicitly cancel when the
|
||||
/// subscription is disposed to clean up associated resources and to avoid having too many watches open at once.
|
||||
private synchronized void cancelWatch() {
|
||||
@@ -355,4 +386,80 @@ class FoundationDbMessagePublisher {
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized void startPresenceRenewal(final ScheduledExecutorService presenceRenewalExecutorService) {
|
||||
final long renewalIntervalMillis =
|
||||
FoundationDbMessageStore.PRESENCE_STALE_THRESHOLD.multipliedBy(4).dividedBy(5).toMillis();
|
||||
|
||||
renewPresenceFuture = presenceRenewalExecutorService.scheduleWithFixedDelay(this::renewPresence,
|
||||
renewalIntervalMillis,
|
||||
renewalIntervalMillis,
|
||||
TimeUnit.MILLISECONDS);
|
||||
}
|
||||
|
||||
private synchronized void renewPresence() {
|
||||
if (state == State.TERMINATED || state == State.ERROR) {
|
||||
return;
|
||||
}
|
||||
|
||||
database.runAsync(transaction -> {
|
||||
setPresence(transaction);
|
||||
return CompletableFuture.completedFuture(null);
|
||||
})
|
||||
.whenComplete((_, throwable) -> {
|
||||
if (throwable != null) {
|
||||
LOGGER.warn("Failed to renew presence; will terminate publisher", throwable);
|
||||
terminateWithError(throwable);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void setPresence(final Transaction transaction) {
|
||||
transaction.set(presenceKey, FoundationDbMessageStore.getPresenceValue(clock.instant(), streamId));
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
synchronized void clearPresence() {
|
||||
if (renewPresenceFuture != null) {
|
||||
renewPresenceFuture.cancel(true);
|
||||
}
|
||||
|
||||
if (!terminateOnQueueEmpty) {
|
||||
database.runAsync(transaction -> transaction.get(presenceKey).thenAccept(presenceValue -> {
|
||||
if (presenceValue == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
final byte[] presenceServerId = FoundationDbMessageStore.getPresenceServerId(presenceValue);
|
||||
final int presenceStreamId = FoundationDbMessageStore.getPresenceStreamId(presenceValue);
|
||||
|
||||
if (Arrays.equals(presenceServerId, FoundationDbMessageStore.getServerId()) && streamId == presenceStreamId) {
|
||||
transaction.clear(presenceKey);
|
||||
}
|
||||
}))
|
||||
.whenComplete((_, throwable) -> {
|
||||
if (throwable != null) {
|
||||
LOGGER.warn("Failed to clear presence on disposal", throwable);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
synchronized void terminateWithError(final Throwable throwable) {
|
||||
if (state != State.TERMINATED && state != State.ERROR) {
|
||||
setState(State.ERROR, Event.INTERNAL_TRIGGER);
|
||||
}
|
||||
|
||||
emitter.error(throwable);
|
||||
}
|
||||
|
||||
private synchronized void onDispose() {
|
||||
// Unless the state machine is an already terminal state, directly set state to "terminated", since there's no point
|
||||
// in evaluating the state machine when there's no live subscription.
|
||||
if (state != State.TERMINATED && state != State.ERROR) {
|
||||
setState(State.TERMINATED, Event.INTERNAL_TRIGGER);
|
||||
}
|
||||
cancelWatch();
|
||||
clearPresence();
|
||||
}
|
||||
}
|
||||
+318
-44
@@ -2,6 +2,7 @@ package org.whispersystems.textsecuregcm.storage.foundationdb;
|
||||
|
||||
import com.apple.foundationdb.Database;
|
||||
import com.apple.foundationdb.MutationType;
|
||||
import com.apple.foundationdb.Range;
|
||||
import com.apple.foundationdb.Transaction;
|
||||
import com.apple.foundationdb.subspace.Subspace;
|
||||
import com.apple.foundationdb.tuple.Tuple;
|
||||
@@ -9,22 +10,32 @@ import com.apple.foundationdb.tuple.Versionstamp;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.common.hash.Hashing;
|
||||
import io.dropwizard.util.DataSize;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.IdentityHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
import javax.annotation.Nullable;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.MessageStream;
|
||||
import org.whispersystems.textsecuregcm.util.Conversions;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
/// An implementation of a message store backed by FoundationDB.
|
||||
@@ -40,12 +51,21 @@ import org.whispersystems.textsecuregcm.util.Util;
|
||||
/// * {versionstamp_2} => envelope_2
|
||||
public class FoundationDbMessageStore {
|
||||
|
||||
private final Database[] databases;
|
||||
private final Database[][] databasesByEpoch;
|
||||
private final Map<Database, VersionstampClock> versionstampClocks;
|
||||
private final int[] liveEpochs;
|
||||
private final int activeEpoch;
|
||||
private final VersionstampUUIDCipher versionstampUUIDCipher;
|
||||
private final ScheduledExecutorService presenceRenewalExecutorService;
|
||||
private final Clock clock;
|
||||
|
||||
private static final byte[] SERVER_ID = UUIDUtil.toBytes(UUID.randomUUID());
|
||||
private static final int PRESENCE_VALUE_LENGTH = 28;
|
||||
|
||||
private static final Subspace MESSAGES_SUBSPACE = new Subspace(Tuple.from("M"));
|
||||
private static final Duration PRESENCE_STALE_THRESHOLD = Duration.ofMinutes(5);
|
||||
|
||||
@VisibleForTesting
|
||||
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
|
||||
@@ -53,20 +73,59 @@ public class FoundationDbMessageStore {
|
||||
/// 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();
|
||||
|
||||
// We pack the current configuration epoch and shard ID into a single byte of "user data" in each message
|
||||
// versionstamp. We use two bits for the epoch and six for the shard ID.
|
||||
public static final int MAX_EPOCHS = 4;
|
||||
public static final int MAX_SHARDS = 64;
|
||||
|
||||
private static final Counter INSERT_MESSAGE_COUNTER =
|
||||
Metrics.counter(MetricsUtil.name(FoundationDbMessageStore.class, "insertMessage"));
|
||||
|
||||
private static final Timer INSERT_MESSAGE_BATCH_TIMER =
|
||||
Metrics.timer(MetricsUtil.name(FoundationDbMessageStore.class, "insertMessageBatchTimer"));
|
||||
|
||||
private static final Counter DELETE_MESSAGE_COUNTER =
|
||||
Metrics.counter(MetricsUtil.name(FoundationDbMessageStore.class, "deleteMessage"));
|
||||
|
||||
private static final Timer DELETE_MESSAGE_TIMER =
|
||||
Metrics.timer(MetricsUtil.name(FoundationDbMessageStore.class, "deleteMessageTimer"));
|
||||
|
||||
/// 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 messageGuid the versionstamp encrypted/encoded as a version 8 UUID
|
||||
/// @param present whether the device is online
|
||||
public record InsertResult(Optional<Versionstamp> versionstamp, boolean present) {
|
||||
public record InsertResult(Optional<Versionstamp> versionstamp,
|
||||
Optional<UUID> messageGuid,
|
||||
boolean present) {
|
||||
}
|
||||
|
||||
public FoundationDbMessageStore(final Database[] databases,
|
||||
public FoundationDbMessageStore(final Map<Integer, List<Database>> databasesByEpochMap,
|
||||
final int activeEpoch,
|
||||
final VersionstampUUIDCipher versionstampUUIDCipher,
|
||||
final ScheduledExecutorService presenceRenewalExecutorService,
|
||||
final Clock clock) {
|
||||
|
||||
this.databases = databases;
|
||||
final Database[][] databasesByEpochArray = new Database[MAX_EPOCHS][];
|
||||
|
||||
databasesByEpochMap.forEach((epoch, databases) ->
|
||||
databasesByEpochArray[epoch] = databases.toArray(Database[]::new));
|
||||
|
||||
this.databasesByEpoch = databasesByEpochArray;
|
||||
this.liveEpochs = IntStream.range(0, MAX_EPOCHS).filter(e -> databasesByEpochArray[e] != null).toArray();
|
||||
this.activeEpoch = activeEpoch;
|
||||
this.versionstampUUIDCipher = versionstampUUIDCipher;
|
||||
this.presenceRenewalExecutorService = presenceRenewalExecutorService;
|
||||
this.versionstampClocks = databasesByEpochMap.values().stream()
|
||||
.flatMap(List::stream)
|
||||
.distinct()
|
||||
.collect(Collectors.toMap(Function.identity(),
|
||||
db -> new VersionstampClock(db, clock),
|
||||
(_, _) -> {
|
||||
throw new AssertionError("Source stream had duplicates after distinct()");
|
||||
},
|
||||
IdentityHashMap::new));
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
@@ -79,7 +138,15 @@ public class FoundationDbMessageStore {
|
||||
public CompletableFuture<Map<Byte, InsertResult>> insert(final AciServiceIdentifier aciServiceIdentifier,
|
||||
final Map<Byte, MessageProtos.Envelope> messagesByDeviceId) {
|
||||
|
||||
return insert(Map.of(aciServiceIdentifier, messagesByDeviceId))
|
||||
return insert(aciServiceIdentifier, messagesByDeviceId, activeEpoch);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
CompletableFuture<Map<Byte, InsertResult>> insert(final AciServiceIdentifier aciServiceIdentifier,
|
||||
final Map<Byte, MessageProtos.Envelope> messagesByDeviceId,
|
||||
final int epoch) {
|
||||
|
||||
return insert(Map.of(aciServiceIdentifier, messagesByDeviceId), epoch)
|
||||
.thenApply(resultsByServiceIdentifier -> {
|
||||
assert resultsByServiceIdentifier.size() == 1;
|
||||
|
||||
@@ -101,6 +168,16 @@ public class FoundationDbMessageStore {
|
||||
public CompletableFuture<Map<AciServiceIdentifier, Map<Byte, InsertResult>>> insert(
|
||||
final Map<AciServiceIdentifier, Map<Byte, MessageProtos.Envelope>> messagesByServiceIdentifier) {
|
||||
|
||||
return insert(messagesByServiceIdentifier, activeEpoch);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
CompletableFuture<Map<AciServiceIdentifier, Map<Byte, InsertResult>>> insert(
|
||||
final Map<AciServiceIdentifier, Map<Byte, MessageProtos.Envelope>> messagesByServiceIdentifier,
|
||||
final int epoch) {
|
||||
|
||||
final Timer.Sample sample = Timer.start();
|
||||
|
||||
if (messagesByServiceIdentifier.entrySet()
|
||||
.stream()
|
||||
.anyMatch(entry -> entry.getValue().isEmpty())) {
|
||||
@@ -117,7 +194,7 @@ public class FoundationDbMessageStore {
|
||||
|
||||
final Map<Integer, List<Map.Entry<AciServiceIdentifier, Map<Byte, MessageProtos.Envelope>>>> messagesByShardId =
|
||||
messagesByServiceIdentifier.entrySet().stream()
|
||||
.collect(Collectors.groupingBy(entry -> hashAciToShardNumber(entry.getKey())));
|
||||
.collect(Collectors.groupingBy(entry -> hashAciToShardNumber(entry.getKey(), epoch)));
|
||||
|
||||
final List<CompletableFuture<Map<AciServiceIdentifier, Map<Byte, InsertResult>>>> chunkFutures =
|
||||
new ArrayList<>();
|
||||
@@ -133,7 +210,7 @@ public class FoundationDbMessageStore {
|
||||
.sum();
|
||||
|
||||
if (estimatedTransactionSize > MAX_MESSAGE_CHUNK_SIZE) {
|
||||
chunkFutures.add(insertChunk(shardId, messagesForShard.subList(start, current)));
|
||||
chunkFutures.add(insertChunk(shardId, epoch, messagesForShard.subList(start, current)));
|
||||
|
||||
start = current;
|
||||
estimatedTransactionSize = 0;
|
||||
@@ -143,7 +220,7 @@ public class FoundationDbMessageStore {
|
||||
}
|
||||
|
||||
assert start < messagesForShard.size();
|
||||
chunkFutures.add(insertChunk(shardId, messagesForShard.subList(start, messagesForShard.size())));
|
||||
chunkFutures.add(insertChunk(shardId, epoch, messagesForShard.subList(start, messagesForShard.size())));
|
||||
});
|
||||
|
||||
return CompletableFuture.allOf(chunkFutures.toArray(CompletableFuture[]::new))
|
||||
@@ -152,11 +229,18 @@ public class FoundationDbMessageStore {
|
||||
.reduce(new HashMap<>(), (a, b) -> {
|
||||
a.putAll(b);
|
||||
return a;
|
||||
}));
|
||||
}))
|
||||
.whenComplete((_, throwable) -> {
|
||||
if (throwable == null) {
|
||||
sample.stop(INSERT_MESSAGE_BATCH_TIMER);
|
||||
INSERT_MESSAGE_COUNTER.increment(messagesByServiceIdentifier.values().stream().mapToInt(Map::size).sum());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private CompletableFuture<Map<AciServiceIdentifier, Map<Byte, InsertResult>>> insertChunk(
|
||||
final int shardId,
|
||||
final int epoch,
|
||||
final List<Map.Entry<AciServiceIdentifier, Map<Byte, MessageProtos.Envelope>>> messagesByAccountIdentifier) {
|
||||
|
||||
final Map<AciServiceIdentifier, CompletableFuture<Map<Byte, Boolean>>> insertFuturesByAci = new HashMap<>();
|
||||
@@ -168,9 +252,9 @@ public class FoundationDbMessageStore {
|
||||
.map(MessageProtos.Envelope::getEphemeral)
|
||||
.orElseThrow(() -> new IllegalStateException("One or more bundles is empty"));
|
||||
|
||||
return databases[shardId].runAsync(transaction -> {
|
||||
return getDatabases(epoch)[shardId].runAsync(transaction -> {
|
||||
messagesByAccountIdentifier.forEach(entry ->
|
||||
insertFuturesByAci.put(entry.getKey(), insert(entry.getKey(), entry.getValue(), transaction)));
|
||||
insertFuturesByAci.put(entry.getKey(), insert(entry.getKey(), entry.getValue(), epoch, shardId, transaction)));
|
||||
|
||||
return CompletableFuture.allOf(insertFuturesByAci.values().toArray(CompletableFuture[]::new))
|
||||
.thenApply(_ -> {
|
||||
@@ -181,7 +265,8 @@ public class FoundationDbMessageStore {
|
||||
.anyMatch(isPresent -> isPresent);
|
||||
if (anyClientPresent || !ephemeral) {
|
||||
return transaction.getVersionstamp()
|
||||
.thenApply(versionstampBytes -> Optional.of(Versionstamp.complete(versionstampBytes, shardId)));
|
||||
.thenApply(versionstampBytes -> Optional.of(Versionstamp.complete(versionstampBytes,
|
||||
packUserData(epoch, shardId))));
|
||||
}
|
||||
return CompletableFuture.completedFuture(Optional.<Versionstamp>empty());
|
||||
});
|
||||
@@ -201,7 +286,11 @@ public class FoundationDbMessageStore {
|
||||
} else {
|
||||
insertResultVersionstamp = Optional.empty();
|
||||
}
|
||||
return new InsertResult(insertResultVersionstamp, presenceEntry.getValue());
|
||||
|
||||
return new InsertResult(insertResultVersionstamp,
|
||||
insertResultVersionstamp.map(versionstamp ->
|
||||
versionstampUUIDCipher.encryptVersionstamp(versionstamp, entry.getKey().uuid(), presenceEntry.getKey())),
|
||||
presenceEntry.getValue());
|
||||
}));
|
||||
})));
|
||||
}
|
||||
@@ -217,6 +306,8 @@ public class FoundationDbMessageStore {
|
||||
/// @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 int epoch,
|
||||
final int shardId,
|
||||
final Transaction transaction) {
|
||||
|
||||
final Map<Byte, CompletableFuture<Boolean>> messageInsertFuturesByDeviceId = messagesByDeviceId.entrySet()
|
||||
@@ -232,7 +323,7 @@ public class FoundationDbMessageStore {
|
||||
if (isPresent || !message.getEphemeral()) {
|
||||
transaction.mutate(MutationType.SET_VERSIONSTAMPED_KEY,
|
||||
getDeviceQueueSubspace(aci, deviceId)
|
||||
.packWithVersionstamp(Tuple.from(Versionstamp.incomplete(hashAciToShardNumber(aci)))), message.toByteArray());
|
||||
.packWithVersionstamp(Tuple.from(Versionstamp.incomplete(packUserData(epoch, shardId)))), message.toByteArray());
|
||||
}
|
||||
|
||||
return isPresent;
|
||||
@@ -251,28 +342,142 @@ public class FoundationDbMessageStore {
|
||||
|
||||
if (anyClientPresent) {
|
||||
transaction.mutate(MutationType.SET_VERSIONSTAMPED_VALUE, getMessagesAvailableWatchKey(aci),
|
||||
Tuple.from(Versionstamp.incomplete(hashAciToShardNumber(aci))).packWithVersionstamp());
|
||||
Tuple.from(Versionstamp.incomplete(packUserData(epoch, shardId))).packWithVersionstamp());
|
||||
}
|
||||
|
||||
return presenceByDeviceId;
|
||||
});
|
||||
}
|
||||
|
||||
public MessageStream getMessages(final AciServiceIdentifier aci, final Device destinationDevice) {
|
||||
return getMessages(aci, destinationDevice, FoundationDbMessageStream.DEFAULT_MAX_MESSAGES_PER_SCAN,
|
||||
FoundationDbMessageStream.DEFAULT_MAX_UNACKNOWLEDGED_MESSAGES, Util.NOOP);
|
||||
CompletableFuture<Void> delete(final AciServiceIdentifier aci, final byte deviceId, final UUID messageGuid) {
|
||||
return delete(aci, deviceId, versionstampUUIDCipher.decryptVersionstamp(messageGuid, aci.uuid(), deviceId));
|
||||
}
|
||||
|
||||
CompletableFuture<Void> delete(final AciServiceIdentifier aci, final byte deviceId, final Versionstamp versionstamp) {
|
||||
final Timer.Sample sample = Timer.start();
|
||||
|
||||
final byte[] messageKey = getDeviceQueueSubspace(aci, deviceId).pack(Tuple.from(versionstamp));
|
||||
|
||||
return databasesByEpoch[getConfigurationEpoch(versionstamp)][getShardId(versionstamp)].runAsync(transaction -> {
|
||||
transaction.clear(messageKey);
|
||||
return CompletableFuture.completedFuture(null);
|
||||
})
|
||||
.thenRun(() -> {
|
||||
sample.stop(DELETE_MESSAGE_TIMER);
|
||||
DELETE_MESSAGE_COUNTER.increment();
|
||||
});
|
||||
}
|
||||
|
||||
public void clearAll(final AciServiceIdentifier aci) {
|
||||
doForAllDatabasesWithMessages(aci, database -> database.run(transaction -> {
|
||||
transaction.clear(getAccountSubspace(aci).range());
|
||||
return null;
|
||||
}));
|
||||
}
|
||||
|
||||
public void clearAll(final AciServiceIdentifier aci, final byte deviceId) {
|
||||
doForAllDatabasesWithMessages(aci, database -> database.run(transaction -> {
|
||||
transaction.clear(getDeviceSubspace(aci, deviceId).range());
|
||||
return null;
|
||||
}));
|
||||
}
|
||||
|
||||
private void doForAllDatabasesWithMessages(final AciServiceIdentifier aci, final Consumer<Database> action) {
|
||||
IntStream.range(0, databasesByEpoch.length)
|
||||
.filter(epoch -> databasesByEpoch[epoch] != null)
|
||||
.mapToObj(epoch -> databasesByEpoch[epoch][hashAciToShardNumber(aci, epoch)])
|
||||
.distinct()
|
||||
.forEach(action);
|
||||
}
|
||||
|
||||
public FoundationDbMessageStream getMessages(final AciServiceIdentifier aci, final byte deviceId) {
|
||||
return getMessages(aci, deviceId, FoundationDbMessageStream.DEFAULT_MAX_MESSAGES_PER_SCAN, Util.NOOP);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
MessageStream getMessages(final AciServiceIdentifier aci, final Device destinationDevice,
|
||||
final int maxMessagesPerScan, final int maxUnacknowledgedMessages, final Runnable doAfterCleanup) {
|
||||
return new FoundationDbMessageStream(getDeviceQueueSubspace(aci, destinationDevice.getId()),
|
||||
getMessagesAvailableWatchKey(aci),
|
||||
getShardForAci(aci),
|
||||
new MessageGuidCodec(aci.uuid(), destinationDevice.getId(), versionstampUUIDCipher),
|
||||
FoundationDbMessageStream getMessages(final AciServiceIdentifier aci,
|
||||
final byte deviceId,
|
||||
final int maxMessagesPerScan,
|
||||
final Runnable doAfterCleanup) {
|
||||
|
||||
// For each configured database epoch, which database held (or holds) the messages for this ACI/device pair?
|
||||
final Database[] databasesForQueueByEpoch = new Database[databasesByEpoch.length];
|
||||
|
||||
for (final int epoch : liveEpochs) {
|
||||
databasesForQueueByEpoch[epoch] = getShardForAci(aci, epoch);
|
||||
}
|
||||
|
||||
return new FoundationDbMessageStream(this,
|
||||
aci,
|
||||
deviceId,
|
||||
databasesForQueueByEpoch,
|
||||
new MessageGuidCodec(aci.uuid(), deviceId, versionstampUUIDCipher),
|
||||
maxMessagesPerScan,
|
||||
maxUnacknowledgedMessages,
|
||||
doAfterCleanup);
|
||||
doAfterCleanup,
|
||||
presenceRenewalExecutorService,
|
||||
clock);
|
||||
}
|
||||
|
||||
/// Record the versionstamp for the current time in each database's versionstamp clock.
|
||||
public void recordVersionstamps() {
|
||||
for (VersionstampClock versionstampClock : versionstampClocks.values()) {
|
||||
versionstampClock.recordVersionstampAndTime();
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove any entries from each database's versionstamp-clock namespace that are strictly older than the given timestamp.
|
||||
///
|
||||
/// @param oldestRetainedEntryTimestamp the earliest time for which we still want to be able to obtain a versionstamp
|
||||
public void expireOldVersionstamps(final Instant oldestRetainedEntryTimestamp) {
|
||||
for (VersionstampClock versionstampClock : versionstampClocks.values()) {
|
||||
versionstampClock.clearExpiredEntries(oldestRetainedEntryTimestamp);
|
||||
}
|
||||
}
|
||||
|
||||
/// Delete messages for the given devices that were inserted before the given time.
|
||||
///
|
||||
/// This issues one range delete for every account/device pair in the map for each actual underlying FoundationDB
|
||||
/// cluster that ever hosted that account in a configured epoch (not just the current epoch). While range deletes are
|
||||
/// efficient, they can potentially induce significant load on the storage process, so callers should be judicious
|
||||
/// with flow control when calling this method.
|
||||
///
|
||||
/// @param accountDeviceIdentifiers a map from ACI to the list of device IDs for which expired messages should be
|
||||
/// trimmed. Note that, depending on the sharding schema of the configured message store, it is possible that we will
|
||||
/// issue a range clear for every device in a single transaction. One range clear involves two keys, each of which has
|
||||
/// an ACI, device ID, and versionstamp, along with overhead to identify the relevant subspace; given the 10MB
|
||||
/// transaction limit and a healthy margin for safety, this means there should be well under 100,000 total
|
||||
/// account/device pairs supplied in a single call to this method.
|
||||
///
|
||||
/// @param cutoffTime the expiration threshold. Messages inserted before this time may be deleted; messages inserted
|
||||
/// after it will not be. Deletion depends on the underlying [versionstamp clocks][VersionstampClock] being kept up to
|
||||
/// date.
|
||||
public void deleteMessagesBefore(final Map<AciServiceIdentifier, List<Byte>> accountDeviceIdentifiers, final Instant cutoffTime) {
|
||||
final Map<Database, List<Subspace>> queueSubspacesToTrimByDatabase = new IdentityHashMap<>();
|
||||
|
||||
accountDeviceIdentifiers.forEach((aci, deviceIds) -> {
|
||||
for (final byte deviceId : deviceIds) {
|
||||
final Subspace queueSubspace = getDeviceQueueSubspace(aci, deviceId);
|
||||
IntStream.of(liveEpochs)
|
||||
.mapToObj(e -> getShardForAci(aci, e))
|
||||
.distinct()
|
||||
.forEach(database -> queueSubspacesToTrimByDatabase.computeIfAbsent(database, _ -> new ArrayList<>()).add(queueSubspace));
|
||||
}
|
||||
});
|
||||
|
||||
queueSubspacesToTrimByDatabase.forEach((database, queueSubspaces) -> {
|
||||
// It's OK that this puts reading the versionstamp in a separate transaction from the deletes; versionstamp clock
|
||||
// entries are effectively immutable and we're looking for one that was written presumably very far in the past,
|
||||
// so there's no conflict to avoid
|
||||
versionstampClocks.get(database).getVersionstamp(cutoffTime).ifPresent(cutoffVersionstamp -> {
|
||||
database.run(transaction -> {
|
||||
transaction.options().setPriorityBatch();
|
||||
for (final Subspace queueSubspace : queueSubspaces) {
|
||||
transaction.clear(new Range(queueSubspace.getKey(), queueSubspace.pack(Tuple.from(cutoffVersionstamp))));
|
||||
}
|
||||
return null;
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
static Versionstamp getVersionstamp(final byte[] messageKey) {
|
||||
@@ -280,14 +485,46 @@ public class FoundationDbMessageStore {
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
Database getShardForAci(final AciServiceIdentifier aci) {
|
||||
return databases[hashAciToShardNumber(aci)];
|
||||
Database getShardForAci(final AciServiceIdentifier aci, final int epoch) {
|
||||
return getDatabases(epoch)[hashAciToShardNumber(aci, epoch)];
|
||||
}
|
||||
|
||||
private Database[] getDatabases(final int epoch) {
|
||||
if (databasesByEpoch[epoch] == null) {
|
||||
throw new IllegalStateException("Epoch (%d) not in static configuration".formatted(epoch));
|
||||
}
|
||||
|
||||
return databasesByEpoch[epoch];
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
int hashAciToShardNumber(final AciServiceIdentifier aci) {
|
||||
int hashAciToShardNumber(final AciServiceIdentifier aci, final int epoch) {
|
||||
// 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);
|
||||
return Hashing.consistentHash(aci.uuid().getLeastSignificantBits(), getDatabases(epoch).length);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static int packUserData(final int epoch, final int shardId) {
|
||||
if (epoch < 0 || epoch >= MAX_EPOCHS) {
|
||||
throw new IllegalArgumentException("Epoch (%d) outside of allowable range (0 to %d, exclusive)".formatted(
|
||||
epoch, MAX_EPOCHS));
|
||||
}
|
||||
|
||||
if (shardId < 0 || shardId >= MAX_SHARDS) {
|
||||
throw new IllegalArgumentException("Shard ID (%d) outside of allowable range (0 to %d, exclusive)".formatted(
|
||||
epoch, MAX_SHARDS));
|
||||
}
|
||||
|
||||
return epoch << 6 | shardId;
|
||||
}
|
||||
|
||||
static int getConfigurationEpoch(final Versionstamp versionstamp) {
|
||||
return versionstamp.getUserVersion() >> 6 & 0x03;
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static int getShardId(final Versionstamp versionstamp) {
|
||||
return versionstamp.getUserVersion() & 0x3f;
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
@@ -309,19 +546,56 @@ public class FoundationDbMessageStore {
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
byte[] getPresenceKey(final AciServiceIdentifier aci, final byte deviceId) {
|
||||
return getDeviceSubspace(aci, deviceId).pack("p");
|
||||
static byte[] getServerId() {
|
||||
return SERVER_ID;
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
boolean isClientPresent(final byte[] presenceValueBytes) {
|
||||
if (presenceValueBytes == null) {
|
||||
static byte[] getPresenceKey(final AciServiceIdentifier aci, final byte deviceId) {
|
||||
return getDeviceSubspace(aci, deviceId).pack("p");
|
||||
}
|
||||
|
||||
static byte[] getPresenceValue(final Instant timestamp, final int streamId) {
|
||||
return ByteBuffer.allocate(PRESENCE_VALUE_LENGTH)
|
||||
.put(SERVER_ID)
|
||||
.putInt(streamId)
|
||||
.putLong(timestamp.toEpochMilli())
|
||||
.array();
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static byte[] getPresenceServerId(final byte[] presenceValue) {
|
||||
if (presenceValue.length != PRESENCE_VALUE_LENGTH) {
|
||||
throw new IllegalArgumentException("Unexpected presence value length: " + presenceValue.length);
|
||||
}
|
||||
|
||||
return Arrays.copyOfRange(presenceValue, 0, 16);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static int getPresenceStreamId(final byte[] presenceValue) {
|
||||
if (presenceValue.length != PRESENCE_VALUE_LENGTH) {
|
||||
throw new IllegalArgumentException("Unexpected presence value length: " + presenceValue.length);
|
||||
}
|
||||
|
||||
return ByteBuffer.wrap(presenceValue).getInt(16);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static Instant getPresenceTimestamp(final byte[] presenceValue) {
|
||||
if (presenceValue.length != PRESENCE_VALUE_LENGTH) {
|
||||
throw new IllegalArgumentException("Unexpected presence value length: " + presenceValue.length);
|
||||
}
|
||||
|
||||
return Instant.ofEpochMilli(ByteBuffer.wrap(presenceValue).getLong(20));
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
boolean isClientPresent(@Nullable final byte[] presenceValue) {
|
||||
if (presenceValue == null) {
|
||||
return false;
|
||||
}
|
||||
final long presenceValue = Conversions.byteArrayToLong(presenceValueBytes);
|
||||
// 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) <= PRESENCE_STALE_THRESHOLD.toSeconds();
|
||||
|
||||
return Duration.between(getPresenceTimestamp(presenceValue), clock.instant()).compareTo(PRESENCE_STALE_THRESHOLD) <= 0;
|
||||
}
|
||||
}
|
||||
Loaded 100 of 214 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user