mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-12-01 05:56:47 +00:00
Compare commits
14
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d7711e235b | ||
|
|
5174550ef3 | ||
|
|
d0fcb9ab54 | ||
|
|
375150a8c3 | ||
|
|
cb28614721 | ||
|
|
f02caf78cd | ||
|
|
8fd72549fb | ||
|
|
1e4774820f | ||
|
|
48cdad7e57 | ||
|
|
392bab5b60 | ||
|
|
6b67604fe7 | ||
|
|
67a03f81b9 | ||
|
|
90b75cbf22 | ||
|
|
4dede4acad |
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
|
||||
|
||||
@@ -18,13 +18,13 @@ jobs:
|
||||
id-token: write
|
||||
contents: read
|
||||
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 }}
|
||||
|
||||
@@ -25,9 +25,9 @@ jobs:
|
||||
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
|
||||
|
||||
@@ -79,10 +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==
|
||||
profileAvatarsZkConfig.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
|
||||
|
||||
@@ -318,18 +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
|
||||
|
||||
profileAvatarsZkConfig:
|
||||
serverSecret: secret://profileAvatarsZkConfig.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
|
||||
|
||||
+20
-16
@@ -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;
|
||||
@@ -67,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
|
||||
@@ -130,6 +131,11 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
@JsonProperty
|
||||
private GcpAttachmentsConfiguration gcpAttachments;
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
@JsonProperty
|
||||
private BackupConfiguration backup = new BackupConfiguration();
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
@JsonProperty
|
||||
@@ -220,11 +226,6 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
@JsonProperty
|
||||
private PaymentsServiceConfiguration paymentsService;
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
private ZkConfig zkConfig;
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
@@ -233,12 +234,12 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
private GenericZkConfig backupsZkConfig;
|
||||
private GenericZkConfig chatZkConfig;
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
private GenericZkConfig profileAvatarsZkConfig;
|
||||
private ZkConfig groupsZkConfig;
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@@ -428,6 +429,10 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
return gcpAttachments;
|
||||
}
|
||||
|
||||
public BackupConfiguration getBackupConfiguration() {
|
||||
return backup;
|
||||
}
|
||||
|
||||
public FaultTolerantRedisClusterFactory getCacheClusterConfiguration() {
|
||||
return cacheCluster;
|
||||
}
|
||||
@@ -492,20 +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;
|
||||
}
|
||||
|
||||
public GenericZkConfig getProfileAvatarsZkConfig() {
|
||||
return profileAvatarsZkConfig;
|
||||
/// ZK secret shared with Groups Service
|
||||
public ZkConfig getGroupsZkConfig() {
|
||||
return groupsZkConfig;
|
||||
}
|
||||
|
||||
public RemoteConfigConfiguration getRemoteConfigConfiguration() {
|
||||
|
||||
@@ -914,18 +914,18 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
config.getCdnConfiguration().credentials().accessKeyId().value(),
|
||||
config.getCdnConfiguration().credentials().secretAccessKey().value());
|
||||
|
||||
ServerSecretParams zkSecretParams = new ServerSecretParams(config.getZkConfig().serverSecret().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());
|
||||
GenericServerSecretParams profileAvatarsGenericZkSecretParams = new GenericServerSecretParams(config.getProfileAvatarsZkConfig().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(),
|
||||
@@ -936,7 +936,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
config.getCdn3StorageManagerConfiguration());
|
||||
BackupManager backupManager = new BackupManager(
|
||||
backupsDb,
|
||||
backupsGenericZkSecretParams,
|
||||
chatGenericZkSecretParams,
|
||||
rateLimiters,
|
||||
tusAttachmentGenerator,
|
||||
cdn3BackupCredentialGenerator,
|
||||
@@ -944,7 +944,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
svrbCredentialsGenerator,
|
||||
secureValueRecoveryBClient,
|
||||
clock,
|
||||
dynamicConfigurationManager);
|
||||
config.getBackupConfiguration());
|
||||
final BackupMetrics backupMetrics = new BackupMetrics();
|
||||
|
||||
final AppleDeviceChecks appleDeviceChecks = new AppleDeviceChecks(
|
||||
@@ -961,7 +961,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
config.getAppleDeviceCheck().teamId(),
|
||||
config.getAppleDeviceCheck().bundleId());
|
||||
|
||||
final DonationPermitsManager donationPermitsManager = new DonationPermitsManager(donationPermits, zkSecretParams,
|
||||
final DonationPermitsManager donationPermitsManager = new DonationPermitsManager(donationPermits, groupZkSecretParams,
|
||||
clock);
|
||||
|
||||
final SubscriptionManager subscriptionManager = new SubscriptionManager(subscriptions,
|
||||
@@ -1054,7 +1054,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,
|
||||
@@ -1071,7 +1071,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
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, profileAvatarsGenericZkSecretParams, 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),
|
||||
@@ -1096,14 +1096,13 @@ 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, profileCdnPolicyGenerator, profileAvatarsGenericZkSecretParams, zkSecretParams, rateLimiters, clock),
|
||||
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 SubscriptionsGrpcService(clock, config.getSubscription(), config.getOneTimeDonations(), subscriptionManager,
|
||||
donationPermitsManager, stripeManager, braintreeManager, googlePlayBillingManager, appleAppStoreManager,
|
||||
profileBadgeConverter, bankMandateTranslator, dynamicConfigurationManager),
|
||||
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))
|
||||
@@ -1238,14 +1237,14 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
new DirectoryV2Controller(directoryV2CredentialsGenerator),
|
||||
new DonationController(clock, zkReceiptOperations, redeemedReceiptsManager, accountsManager, config.getBadges(),
|
||||
ReceiptCredentialPresentation::new, donationPermitsManager, rateLimiters),
|
||||
new KeysController(rateLimiters, keysManager, accountsManager, zkSecretParams, Clock.systemUTC()),
|
||||
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,
|
||||
zkSecretParams, zkProfileOperations, batchIdentityCheckExecutor),
|
||||
groupZkSecretParams, zkProfileOperations, batchIdentityCheckExecutor),
|
||||
new ProvisioningController(rateLimiters, provisioningManager),
|
||||
new RegistrationController(accountsManager, phoneVerificationTokenManager, registrationLockVerificationManager,
|
||||
rateLimiters, registrationFraudChecker),
|
||||
@@ -1259,7 +1258,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
dynamicConfigurationManager, experimentEnrollmentManager, clock),
|
||||
new SubscriptionController(clock, config.getSubscription(), config.getOneTimeDonations(),
|
||||
subscriptionManager, stripeManager, braintreeManager, googlePlayBillingManager, appleAppStoreManager,
|
||||
profileBadgeConverter, bankMandateTranslator, donationPermitsManager, dynamicConfigurationManager),
|
||||
profileBadgeConverter, bankMandateTranslator, donationPermitsManager,
|
||||
config.getBackupConfiguration().maxTotalMediaSize()),
|
||||
new OneTimeDonationController(clock, config.getOneTimeDonations(), stripeManager, braintreeManager,
|
||||
payPalDonationsTranslator, zkReceiptOperations, issuedReceiptsManager, oneTimeDonationsManager,
|
||||
donationPermitsManager)
|
||||
|
||||
@@ -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(
|
||||
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
+5
@@ -45,6 +45,11 @@ public class ConfiguredProfileBadgeConverter implements ProfileBadgeConverter, B
|
||||
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,
|
||||
|
||||
+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);
|
||||
}
|
||||
}
|
||||
-8
@@ -69,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();
|
||||
@@ -143,10 +139,6 @@ public class DynamicConfiguration {
|
||||
return restDeprecation;
|
||||
}
|
||||
|
||||
public DynamicBackupConfiguration getBackupConfiguration() {
|
||||
return backup;
|
||||
}
|
||||
|
||||
public DynamicCarrierDataLookupConfiguration getCarrierDataLookupConfiguration() {
|
||||
return carrierDataLookup;
|
||||
}
|
||||
|
||||
+96
-97
@@ -8,6 +8,7 @@ import static org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil.getClientP
|
||||
|
||||
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;
|
||||
@@ -34,9 +35,9 @@ 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;
|
||||
@@ -45,7 +46,7 @@ import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
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;
|
||||
@@ -74,6 +75,8 @@ 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.SubscriptionInvalidAmountException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorException;
|
||||
import org.whispersystems.textsecuregcm.util.ExactlySize;
|
||||
import org.whispersystems.textsecuregcm.util.HeaderUtils;
|
||||
|
||||
@@ -168,14 +171,15 @@ public class OneTimeDonationController {
|
||||
})))
|
||||
@ApiResponse(responseCode = "401", description = "Donation permit was invalid or already spent")
|
||||
@RateLimitedByIp(RateLimiters.For.ONE_TIME_DONATION)
|
||||
public CompletableFuture<Response> createBoostPaymentIntent(
|
||||
@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) {
|
||||
@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");
|
||||
@@ -195,11 +199,11 @@ public class OneTimeDonationController {
|
||||
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
|
||||
}
|
||||
|
||||
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());
|
||||
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());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -245,34 +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(
|
||||
@ManagedAsync
|
||||
public CreatePayPalBoostResponse createPayPalBoost(
|
||||
@Auth final Optional<AuthenticatedDevice> authenticatedAccount,
|
||||
@NotNull @Valid final CreatePayPalBoostRequest request,
|
||||
@Context final ContainerRequestContext containerRequestContext) {
|
||||
@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);
|
||||
final OneTimeDonationUtil.LocalizedPayPalDonationLineItem localizedLineItem = OneTimeDonationUtil.localizePayPalDonationLineItem(
|
||||
payPalDonationsTranslator, acceptableLanguages);
|
||||
return braintreeManager.createOneTimePayment(request.currency.toUpperCase(Locale.ROOT), request.amount,
|
||||
localizedLineItem.locale().toLanguageTag(),
|
||||
request.returnUrl, request.cancelUrl, localizedLineItem.itemName());
|
||||
})
|
||||
.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 {
|
||||
@@ -289,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(
|
||||
@ManagedAsync
|
||||
public ConfirmPayPalBoostResponse confirmPayPalBoost(
|
||||
@Auth final Optional<AuthenticatedDevice> authenticatedAccount,
|
||||
@NotNull @Valid final ConfirmPayPalBoostRequest request,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent) {
|
||||
@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 {
|
||||
@@ -339,77 +339,76 @@ public class OneTimeDonationController {
|
||||
@Path("/receipt_credentials")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public CompletableFuture<Response> createBoostReceiptCredentials(
|
||||
@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<Optional<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(maybePaymentDetails -> {
|
||||
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();
|
||||
});
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
+15
-18
@@ -48,6 +48,8 @@ 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;
|
||||
@@ -67,7 +69,6 @@ import org.whispersystems.textsecuregcm.badges.BadgeTranslator;
|
||||
import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.SubscriptionConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.SubscriptionLevelConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimitedByIp;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
@@ -75,7 +76,6 @@ import org.whispersystems.textsecuregcm.mappers.SubscriptionExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.DonationPermitsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.storage.SubscriberCredentials;
|
||||
import org.whispersystems.textsecuregcm.storage.SubscriptionManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Subscriptions;
|
||||
@@ -114,7 +114,7 @@ public class SubscriptionController {
|
||||
private final BadgeTranslator badgeTranslator;
|
||||
private final BankMandateTranslator bankMandateTranslator;
|
||||
private final DonationPermitsManager donationPermitsManager;
|
||||
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
|
||||
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";
|
||||
@@ -132,7 +132,7 @@ public class SubscriptionController {
|
||||
BadgeTranslator badgeTranslator,
|
||||
BankMandateTranslator bankMandateTranslator,
|
||||
DonationPermitsManager donationPermitsManager,
|
||||
DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
|
||||
long backupMediaStorageAllowanceBytes) {
|
||||
this.subscriptionManager = subscriptionManager;
|
||||
this.clock = Objects.requireNonNull(clock);
|
||||
this.subscriptionConfiguration = Objects.requireNonNull(subscriptionConfiguration);
|
||||
@@ -144,7 +144,7 @@ public class SubscriptionController {
|
||||
this.badgeTranslator = Objects.requireNonNull(badgeTranslator);
|
||||
this.bankMandateTranslator = Objects.requireNonNull(bankMandateTranslator);
|
||||
this.donationPermitsManager = donationPermitsManager;
|
||||
this.dynamicConfigurationManager = Objects.requireNonNull(dynamicConfigurationManager);
|
||||
this.backupMediaStorageAllowanceBytes = backupMediaStorageAllowanceBytes;
|
||||
}
|
||||
|
||||
|
||||
@@ -152,14 +152,12 @@ public class SubscriptionController {
|
||||
GetSubscriptionConfigurationResponse buildGetSubscriptionConfigurationResponse(
|
||||
final List<Locale> acceptableLanguages) {
|
||||
|
||||
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())));
|
||||
|
||||
@@ -315,7 +313,8 @@ 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);
|
||||
@@ -325,10 +324,8 @@ public class SubscriptionController {
|
||||
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());
|
||||
}
|
||||
@@ -350,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);
|
||||
|
||||
@@ -754,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);
|
||||
|
||||
@@ -776,7 +773,7 @@ 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);
|
||||
|
||||
@@ -94,6 +94,10 @@ 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();
|
||||
|
||||
+45
-28
@@ -8,6 +8,7 @@ import static org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil.getClientP
|
||||
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;
|
||||
@@ -21,18 +22,18 @@ 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.one_time_donations.AmountAboveSepaLimitError;
|
||||
import org.signal.chat.one_time_donations.AmountBelowMinimumError;
|
||||
import org.signal.chat.one_time_donations.ConfirmPayPalBoostRequest;
|
||||
import org.signal.chat.one_time_donations.ConfirmPayPalBoostResponse;
|
||||
import org.signal.chat.one_time_donations.CreateBoostReceiptCredentialsRequest;
|
||||
import org.signal.chat.one_time_donations.CreateBoostReceiptCredentialsResponse;
|
||||
import org.signal.chat.one_time_donations.CreateBoostRequest;
|
||||
import org.signal.chat.one_time_donations.CreateBoostResponse;
|
||||
import org.signal.chat.one_time_donations.CreatePayPalBoostRequest;
|
||||
import org.signal.chat.one_time_donations.CreatePayPalBoostResponse;
|
||||
import org.signal.chat.one_time_donations.SimpleOneTimeDonationsGrpc;
|
||||
import org.signal.chat.subscriptions.PaymentRequired;
|
||||
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;
|
||||
@@ -53,6 +54,8 @@ 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 {
|
||||
|
||||
@@ -91,7 +94,8 @@ public class OneTimeDonationsGrpcService extends SimpleOneTimeDonationsGrpc.OneT
|
||||
}
|
||||
|
||||
@Override
|
||||
public CreateBoostResponse createBoost(final CreateBoostRequest request) throws RateLimitExceededException {
|
||||
public CreateBoostResponse createBoost(final CreateBoostRequest request)
|
||||
throws RateLimitExceededException {
|
||||
RateLimitUtil.rateLimitByRemoteAddress(rateLimiters.forDescriptor(RateLimiters.For.ONE_TIME_DONATION));
|
||||
|
||||
try {
|
||||
@@ -144,16 +148,23 @@ public class OneTimeDonationsGrpcService extends SimpleOneTimeDonationsGrpc.OneT
|
||||
.setAmountAboveSepaLimit(AmountAboveSepaLimitError.newBuilder()
|
||||
.setMaximum(r.maximum().toString()).build()).build();
|
||||
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.Success _ -> {
|
||||
final com.stripe.model.PaymentIntent paymentIntent = stripeManager.createPaymentIntent(
|
||||
request.getCurrency(), request.getAmount(), request.getLevel(),
|
||||
getClientPlatform(RequestAttributesUtil.getUserAgent().orElse(null))).join();
|
||||
yield CreateBoostResponse.newBuilder().setClientSecret(paymentIntent.getClientSecret()).build();
|
||||
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) {
|
||||
public CreatePayPalBoostResponse createPayPalBoost(final CreatePayPalBoostRequest request) throws IOException {
|
||||
|
||||
final OneTimeDonationUtil.OneTimeDonationRequestValidationResult validationResult =
|
||||
OneTimeDonationUtil.validateOneTimeDonationRequest(
|
||||
@@ -185,7 +196,7 @@ public class OneTimeDonationsGrpcService extends SimpleOneTimeDonationsGrpc.OneT
|
||||
braintreeManager.createOneTimePayment(
|
||||
request.getCurrency().toUpperCase(Locale.ROOT), request.getAmount(),
|
||||
localizedLineItem.locale().toLanguageTag(), request.getReturnUrl(), request.getCancelUrl(),
|
||||
localizedLineItem.itemName()).join();
|
||||
localizedLineItem.itemName());
|
||||
yield CreatePayPalBoostResponse.newBuilder()
|
||||
.setResult(CreatePayPalBoostResponse.CreatePayPalBoostResult.newBuilder()
|
||||
.setApprovalUrl(approvalDetails.approvalUrl())
|
||||
@@ -196,7 +207,7 @@ public class OneTimeDonationsGrpcService extends SimpleOneTimeDonationsGrpc.OneT
|
||||
|
||||
@Override
|
||||
public ConfirmPayPalBoostResponse confirmPayPalBoost(final ConfirmPayPalBoostRequest request)
|
||||
throws RateLimitExceededException {
|
||||
throws RateLimitExceededException, IOException {
|
||||
RateLimitUtil.rateLimitByRemoteAddress(rateLimiters.forDescriptor(RateLimiters.For.ONE_TIME_DONATION));
|
||||
|
||||
final OneTimeDonationUtil.OneTimeDonationRequestValidationResult validationResult =
|
||||
@@ -222,33 +233,39 @@ public class OneTimeDonationsGrpcService extends SimpleOneTimeDonationsGrpc.OneT
|
||||
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.AmountAboveSepaLimit _ ->
|
||||
throw new IllegalStateException("SEPA limit should not trigger for PayPal");
|
||||
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.Success _ -> {
|
||||
final BraintreeManager.PayPalChargeSuccessDetails chargeSuccessDetails =
|
||||
braintreeManager.captureOneTimePayment(
|
||||
request.getPayerId(), request.getPaymentId(), request.getPaymentToken(),
|
||||
request.getCurrency(), request.getAmount(), request.getLevel(),
|
||||
getClientPlatform(RequestAttributesUtil.getUserAgent().orElse(null))).join();
|
||||
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) {
|
||||
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()).join();
|
||||
maybePaymentDetails = stripeManager.getPaymentDetails(request.getPaymentIntentId());
|
||||
}
|
||||
case PAYMENT_PROVIDER_BRAINTREE -> {
|
||||
processor = PaymentProvider.BRAINTREE;
|
||||
maybePaymentDetails = braintreeManager.getPaymentDetails(request.getPaymentIntentId()).join();
|
||||
maybePaymentDetails = braintreeManager.getPaymentDetails(request.getPaymentIntentId());
|
||||
}
|
||||
default -> throw GrpcExceptions.fieldViolation("processor", "Unsupported payment processor");
|
||||
}
|
||||
|
||||
+179
@@ -0,0 +1,179 @@
|
||||
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.common.Badge;
|
||||
import org.signal.chat.common.BadgeSvg;
|
||||
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 org.whispersystems.textsecuregcm.entities.Badge badge = levelConfiguration.badge();
|
||||
final Badge commonBadge = Badge.newBuilder()
|
||||
.setId(badge.getId())
|
||||
.setCategory(badge.getCategory())
|
||||
.setName(badge.getName())
|
||||
.setDescription(badge.getDescription())
|
||||
.addAllSprites6(badge.getSprites6())
|
||||
.setSvg(badge.getSvg())
|
||||
.addAllSvgs(badge.getSvgs().stream()
|
||||
.map(s -> BadgeSvg.newBuilder().setLight(s.getLight()).setDark(s.getDark()).build())
|
||||
.toList())
|
||||
.build();
|
||||
final LevelConfiguration.Builder builder = LevelConfiguration.newBuilder().setBadge(commonBadge);
|
||||
if (badge instanceof final PurchasableBadge purchasableBadge) {
|
||||
builder.setBadgeDurationSeconds(purchasableBadge.getDuration().toSeconds());
|
||||
}
|
||||
return builder.build();
|
||||
}
|
||||
}
|
||||
+71
-160
@@ -5,13 +5,11 @@ import static org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil.getPayPalL
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import com.google.protobuf.Empty;
|
||||
import java.math.BigDecimal;
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.time.Clock;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Collectors;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
@@ -19,46 +17,37 @@ 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.subscriptions.CreatePayPalPaymentMethodRequest;
|
||||
import org.signal.chat.subscriptions.CreatePayPalPaymentMethodResponse;
|
||||
import org.signal.chat.subscriptions.CreatePaymentMethodRequest;
|
||||
import org.signal.chat.subscriptions.CreatePaymentMethodResponse;
|
||||
import org.signal.chat.subscriptions.DeleteSubscriberRequest;
|
||||
import org.signal.chat.subscriptions.DeleteSubscriberResponse;
|
||||
import org.signal.chat.subscriptions.GetBankMandateRequest;
|
||||
import org.signal.chat.subscriptions.GetBankMandateResponse;
|
||||
import org.signal.chat.subscriptions.GetConfigurationRequest;
|
||||
import org.signal.chat.subscriptions.GetConfigurationResponse;
|
||||
import org.signal.chat.subscriptions.GetReceiptCredentialsRequest;
|
||||
import org.signal.chat.subscriptions.GetReceiptCredentialsResponse;
|
||||
import org.signal.chat.subscriptions.GetSubscriptionInformationRequest;
|
||||
import org.signal.chat.subscriptions.GetSubscriptionInformationResponse;
|
||||
import org.signal.chat.subscriptions.PaymentMethod;
|
||||
import org.signal.chat.subscriptions.PaymentRequired;
|
||||
import org.signal.chat.subscriptions.SetDefaultPaymentMethodRequest;
|
||||
import org.signal.chat.subscriptions.SetDefaultPaymentMethodResponse;
|
||||
import org.signal.chat.subscriptions.SetIapSubscriptionRequest;
|
||||
import org.signal.chat.subscriptions.SetIapSubscriptionResponse;
|
||||
import org.signal.chat.subscriptions.SetSubscriptionLevelRequest;
|
||||
import org.signal.chat.subscriptions.SetSubscriptionLevelResponse;
|
||||
import org.signal.chat.subscriptions.SimpleSubscriptionsGrpc;
|
||||
import org.signal.chat.subscriptions.UpdateSubscriberRequest;
|
||||
import org.signal.chat.subscriptions.UpdateSubscriberResponse;
|
||||
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.badges.BadgeTranslator;
|
||||
import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.SubscriptionConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.SubscriptionLevelConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
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.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.storage.SubscriberCredentials;
|
||||
import org.whispersystems.textsecuregcm.storage.SubscriptionManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Subscriptions;
|
||||
@@ -66,7 +55,6 @@ 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.CurrencyConfiguration;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.CustomerAwareSubscriptionPaymentProcessor;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.GooglePlayBillingManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.ProcessorCustomer;
|
||||
@@ -91,41 +79,37 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
|
||||
|
||||
private final Clock clock;
|
||||
private final SubscriptionConfiguration subscriptionConfiguration;
|
||||
private final OneTimeDonationConfiguration oneTimeDonationConfiguration;
|
||||
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 BadgeTranslator badgeTranslator;
|
||||
private final BankMandateTranslator bankMandateTranslator;
|
||||
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
|
||||
|
||||
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 OneTimeDonationConfiguration oneTimeDonationConfiguration, final SubscriptionManager subscriptionManager,
|
||||
final DonationPermitsManager donationPermitsManager, final StripeManager stripeManager,
|
||||
final BraintreeManager braintreeManager, final GooglePlayBillingManager googlePlayBillingManager,
|
||||
final AppleAppStoreManager appleAppStoreManager, final BadgeTranslator badgeTranslator,
|
||||
final BankMandateTranslator bankMandateTranslator,
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
|
||||
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.oneTimeDonationConfiguration = oneTimeDonationConfiguration;
|
||||
this.subscriptionManager = subscriptionManager;
|
||||
this.donationPermitsManager = donationPermitsManager;
|
||||
this.stripeManager = stripeManager;
|
||||
this.braintreeManager = braintreeManager;
|
||||
this.googlePlayBillingManager = googlePlayBillingManager;
|
||||
this.appleAppStoreManager = appleAppStoreManager;
|
||||
this.badgeTranslator = badgeTranslator;
|
||||
this.bankMandateTranslator = bankMandateTranslator;
|
||||
this.dynamicConfigurationManager = dynamicConfigurationManager;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -234,7 +218,8 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
|
||||
}
|
||||
|
||||
@Override
|
||||
public CreatePayPalPaymentMethodResponse createPayPalPaymentMethod(final CreatePayPalPaymentMethodRequest request) {
|
||||
public CreatePayPalPaymentMethodResponse createPayPalPaymentMethod(final CreatePayPalPaymentMethodRequest request)
|
||||
throws IOException {
|
||||
final SubscriberCredentials subscriberCredentials = SubscriberCredentials.process(
|
||||
request.getSubscriberId().toByteArray(), clock);
|
||||
final Locale locale = getPayPalLocale(RequestAttributesUtil.getAvailableAcceptedLocales());
|
||||
@@ -242,7 +227,7 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
|
||||
final BraintreeManager.PayPalBillingAgreementApprovalDetails details = subscriptionManager.addPaymentMethodToCustomer(
|
||||
subscriberCredentials, braintreeManager, getClientPlatform(RequestAttributesUtil.getUserAgent().orElse(null)),
|
||||
(mgr, _) -> mgr.createPayPalBillingAgreement(request.getReturnUrl(), request.getCancelUrl(),
|
||||
locale.toLanguageTag())).join();
|
||||
locale.toLanguageTag()));
|
||||
return CreatePayPalPaymentMethodResponse.newBuilder().setResult(
|
||||
CreatePayPalPaymentMethodResponse.CreatePayPalPaymentMethodResult.newBuilder()
|
||||
.setApprovalUrl(details.approvalUrl()).setToken(details.billingAgreementToken()).build()).build();
|
||||
@@ -259,27 +244,28 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
|
||||
}
|
||||
|
||||
@Override
|
||||
public SetDefaultPaymentMethodResponse setDefaultPaymentMethod(final SetDefaultPaymentMethodRequest request) {
|
||||
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()).join();
|
||||
}
|
||||
default -> throw GrpcExceptions.fieldViolation("request", "No payment method specified");
|
||||
};
|
||||
|
||||
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,
|
||||
@@ -293,6 +279,10 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
|
||||
} 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();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -308,6 +298,8 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
|
||||
return SetDefaultPaymentMethodResponse.newBuilder()
|
||||
.setPaymentMethodNotSetUp(FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build())
|
||||
.build();
|
||||
} catch (final IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -446,7 +438,7 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
|
||||
.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(toProtoPaymentMethod(info.paymentMethod()))
|
||||
.setProcessor(info.paymentProvider().toProto()).setPaymentMethod(info.paymentMethod().toProtoPaymentMethod())
|
||||
.setPaymentProcessing(info.paymentProcessing());
|
||||
if (info.billingCycleAnchor() != null) {
|
||||
subscription.setBillingCycleAnchor(info.billingCycleAnchor().getEpochSecond());
|
||||
@@ -503,99 +495,18 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
|
||||
}
|
||||
}
|
||||
|
||||
private static org.signal.chat.subscriptions.SubscriptionStatus toProtoSubscriptionStatus(
|
||||
private static org.signal.chat.purchase.SubscriptionStatus toProtoSubscriptionStatus(
|
||||
final SubscriptionStatus status) {
|
||||
return switch (status) {
|
||||
case ACTIVE -> org.signal.chat.subscriptions.SubscriptionStatus.SUBSCRIPTION_STATUS_ACTIVE;
|
||||
case INCOMPLETE -> org.signal.chat.subscriptions.SubscriptionStatus.SUBSCRIPTION_STATUS_INCOMPLETE;
|
||||
case PAST_DUE -> org.signal.chat.subscriptions.SubscriptionStatus.SUBSCRIPTION_STATUS_PAST_DUE;
|
||||
case CANCELED -> org.signal.chat.subscriptions.SubscriptionStatus.SUBSCRIPTION_STATUS_CANCELED;
|
||||
case UNPAID -> org.signal.chat.subscriptions.SubscriptionStatus.SUBSCRIPTION_STATUS_UNPAID;
|
||||
case UNKNOWN -> org.signal.chat.subscriptions.SubscriptionStatus.SUBSCRIPTION_STATUS_UNKNOWN;
|
||||
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;
|
||||
};
|
||||
}
|
||||
|
||||
private static PaymentMethod toProtoPaymentMethod(
|
||||
final org.whispersystems.textsecuregcm.subscriptions.PaymentMethod paymentMethod) {
|
||||
if (paymentMethod == null) {
|
||||
return PaymentMethod.PAYMENT_METHOD_UNKNOWN;
|
||||
}
|
||||
return switch (paymentMethod) {
|
||||
case CARD -> PaymentMethod.PAYMENT_METHOD_CARD;
|
||||
case SEPA_DEBIT -> PaymentMethod.PAYMENT_METHOD_SEPA_DEBIT;
|
||||
case IDEAL -> PaymentMethod.PAYMENT_METHOD_IDEAL;
|
||||
case PAYPAL -> PaymentMethod.PAYMENT_METHOD_PAYPAL;
|
||||
case GOOGLE_PLAY_BILLING -> PaymentMethod.PAYMENT_METHOD_GOOGLE_PLAY_BILLING;
|
||||
case APPLE_APP_STORE -> PaymentMethod.PAYMENT_METHOD_APPLE_APP_STORE;
|
||||
case UNKNOWN -> PaymentMethod.PAYMENT_METHOD_UNKNOWN;
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public GetConfigurationResponse getConfiguration(final GetConfigurationRequest request) {
|
||||
final long maxBackupBytes = dynamicConfigurationManager.getConfiguration().getBackupConfiguration()
|
||||
.maxTotalMediaSize();
|
||||
|
||||
final Map<Long, GetConfigurationResponse.BackupLevelConfiguration> backupLevels = subscriptionConfiguration.getBackupLevels()
|
||||
.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey,
|
||||
e -> GetConfigurationResponse.BackupLevelConfiguration.newBuilder().setStorageAllowanceBytes(maxBackupBytes)
|
||||
.setPlayProductId(e.getValue().playProductId()).setMediaTtlDays(e.getValue().mediaTtl().toDays())
|
||||
.build()));
|
||||
|
||||
return GetConfigurationResponse.newBuilder().putAllCurrencies(buildCurrencyConfigurations())
|
||||
.putAllLevels(buildLevelConfigurations()).setBackup(
|
||||
GetConfigurationResponse.BackupConfiguration.newBuilder().putAllLevels(backupLevels)
|
||||
.setFreeTierMediaDays(subscriptionConfiguration.getbackupFreeTierMediaDuration().toDays()).build())
|
||||
.setSepaMaximumEuros(oneTimeDonationConfiguration.sepaMaximumEuros().toString()).build();
|
||||
}
|
||||
|
||||
private Map<String, GetConfigurationResponse.CurrencyConfiguration> buildCurrencyConfigurations() {
|
||||
return SubscriptionsUtil.buildCurrencyConfiguration(List.of(stripeManager, braintreeManager),
|
||||
oneTimeDonationConfiguration, subscriptionConfiguration).entrySet().stream()
|
||||
.collect(Collectors.toMap(Map.Entry::getKey, e -> toProtoCurrencyConfiguration(e.getKey(), e.getValue())));
|
||||
}
|
||||
|
||||
private Map<Long, GetConfigurationResponse.LevelConfiguration> buildLevelConfigurations() {
|
||||
return SubscriptionsUtil.buildDonationLevelsConfiguration(subscriptionConfiguration, oneTimeDonationConfiguration,
|
||||
badgeTranslator, RequestAttributesUtil.getAvailableAcceptedLocales()).entrySet().stream().collect(
|
||||
Collectors.toMap(Map.Entry::getKey, entry -> GetConfigurationResponse.LevelConfiguration.newBuilder()
|
||||
.setBadge(toProtoBadge(entry.getValue().badge())).build()));
|
||||
}
|
||||
|
||||
private static GetConfigurationResponse.CurrencyConfiguration toProtoCurrencyConfiguration(final String currency,
|
||||
final CurrencyConfiguration config) {
|
||||
final GetConfigurationResponse.CurrencyConfiguration.Builder builder = GetConfigurationResponse.CurrencyConfiguration.newBuilder()
|
||||
.setMinimum(config.minimum().toString())
|
||||
.addAllSupportedPaymentMethods(
|
||||
config.supportedPaymentMethods().stream().map(SubscriptionsGrpcService::toProtoPaymentMethod).toList());
|
||||
config.oneTime().forEach((levelId, amounts) -> builder.putOneTime(levelId,
|
||||
GetConfigurationResponse.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 GetConfigurationResponse.Badge toProtoBadge(final Badge badge) {
|
||||
final org.signal.chat.common.Badge commonBadge = org.signal.chat.common.Badge.newBuilder().setId(badge.getId())
|
||||
.setCategory(badge.getCategory()).setName(badge.getName()).setDescription(badge.getDescription())
|
||||
.addAllSprites6(badge.getSprites6()).setSvg(badge.getSvg()).addAllSvgs(badge.getSvgs().stream()
|
||||
.map(s -> org.signal.chat.common.BadgeSvg.newBuilder().setLight(s.getLight()).setDark(s.getDark()).build())
|
||||
.toList()).build();
|
||||
final GetConfigurationResponse.Badge.Builder builder = GetConfigurationResponse.Badge.newBuilder()
|
||||
.setBadge(commonBadge);
|
||||
if (badge instanceof final PurchasableBadge purchasableBadge) {
|
||||
builder.setDurationSeconds(purchasableBadge.getDuration().toSeconds());
|
||||
}
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public GetBankMandateResponse getBankMandate(final GetBankMandateRequest request) {
|
||||
final BankTransferType bankTransferType = switch (request.getBankTransferType()) {
|
||||
|
||||
@@ -162,9 +162,9 @@ public class SubscriptionsUtil {
|
||||
.increment();
|
||||
}
|
||||
|
||||
public static org.signal.chat.subscriptions.ChargeFailure toChargeFailure(final PaymentProvider processor,
|
||||
public static org.signal.chat.purchase.ChargeFailure toChargeFailure(final PaymentProvider processor,
|
||||
final ChargeFailure chargeFailure) {
|
||||
final org.signal.chat.subscriptions.ChargeFailure.Builder builder = org.signal.chat.subscriptions.ChargeFailure.newBuilder()
|
||||
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());
|
||||
|
||||
+1
-1
@@ -114,7 +114,7 @@ public class AcknowledgementMirroringMessageStream implements MessageStream {
|
||||
JdkFlowAdapter.flowPublisherToFlux(redisDynamoDbMessageStream.getMessages())
|
||||
// Mirror demand and termination signals to the FoundationDB message stream
|
||||
.doOnNext(subscriber::handleRedisDynamoDbMessageStreamEntry)
|
||||
.doOnComplete(subscriber::dispose));
|
||||
.doFinally(_ -> subscriber.dispose()));
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -38,7 +38,6 @@ import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager;
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStore;
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStream;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
import reactor.core.observability.micrometer.Micrometer;
|
||||
import reactor.core.publisher.Flux;
|
||||
|
||||
+5
-3
@@ -41,6 +41,7 @@ import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorConfl
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptAlreadyRedeemedException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptRequestedForOpenPaymentException;
|
||||
import org.whispersystems.textsecuregcm.util.ThrowingBiFunction;
|
||||
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
|
||||
|
||||
/**
|
||||
@@ -244,6 +245,7 @@ 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
|
||||
@@ -251,12 +253,12 @@ public class SubscriptionManager {
|
||||
* @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()) {
|
||||
|
||||
+15
-1
@@ -18,6 +18,7 @@ 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 java.util.function.Consumer;
|
||||
import java.util.function.Supplier;
|
||||
@@ -80,6 +81,9 @@ class FoundationDbMessagePublisher {
|
||||
/// 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);
|
||||
@@ -148,7 +152,12 @@ class FoundationDbMessagePublisher {
|
||||
|
||||
this.messagePublisher = Flux.<FoundationDbMessageStreamEntry.Message>create(emitter -> {
|
||||
this.emitter = emitter;
|
||||
emitter.onRequest(_ -> transitionStateOnEvent(Event.DEMAND_REQUESTED));
|
||||
emitter.onRequest(n -> {
|
||||
final long totalRequestedCount = totalRequested.addAndGet(n);
|
||||
if (totalRequestedCount > totalEmitted.get()) {
|
||||
transitionStateOnEvent(Event.DEMAND_REQUESTED);
|
||||
}
|
||||
});
|
||||
emitter.onDispose(this::onDispose);
|
||||
}).doOnSubscribe(_ -> {
|
||||
if (!terminateOnQueueEmpty) {
|
||||
@@ -381,6 +390,7 @@ class FoundationDbMessagePublisher {
|
||||
getMessagesBatch()
|
||||
.thenAccept(messageStreamEntries -> {
|
||||
messageStreamEntries.forEach(emitter::next);
|
||||
totalEmitted.addAndGet(messageStreamEntries.size());
|
||||
transitionStateOnEvent(Event.PUBLISHED_MESSAGES);
|
||||
})
|
||||
.exceptionally(t -> {
|
||||
@@ -453,6 +463,10 @@ class FoundationDbMessagePublisher {
|
||||
|
||||
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);
|
||||
|
||||
|
||||
+59
-81
@@ -36,7 +36,7 @@ import com.braintree.graphql.clientoperation.CreatePayPalOneTimePaymentMutation;
|
||||
import com.braintree.graphql.clientoperation.TokenizePayPalBillingAgreementMutation;
|
||||
import com.braintree.graphql.clientoperation.TokenizePayPalOneTimePaymentMutation;
|
||||
import com.braintree.graphql.clientoperation.VaultPaymentMethodMutation;
|
||||
import jakarta.ws.rs.ServiceUnavailableException;
|
||||
import java.io.IOException;
|
||||
import java.math.BigDecimal;
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
@@ -44,7 +44,6 @@ import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import okio.Buffer;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
@@ -69,7 +68,7 @@ class BraintreeGraphqlClient {
|
||||
this.httpClient = httpClient;
|
||||
try {
|
||||
this.graphqlUri = new URI(graphqlUri);
|
||||
} catch (URISyntaxException e) {
|
||||
} catch (final URISyntaxException e) {
|
||||
throw new IllegalArgumentException("Invalid URI", e);
|
||||
}
|
||||
// “public”/“private” key is a bit of a misnomer, but we follow the upstream nomenclature
|
||||
@@ -77,36 +76,32 @@ class BraintreeGraphqlClient {
|
||||
this.authorizationHeader = "Basic " + Base64.getEncoder().encodeToString((publicKey + ":" + privateKey).getBytes());
|
||||
}
|
||||
|
||||
CompletableFuture<CreatePayPalOneTimePaymentMutation.CreatePayPalOneTimePayment> createPayPalOneTimePayment(
|
||||
CreatePayPalOneTimePaymentMutation.CreatePayPalOneTimePayment createPayPalOneTimePayment(
|
||||
final BigDecimal amount, final String currency, final String returnUrl,
|
||||
final String cancelUrl, final String locale, final String localizedLineItemName) {
|
||||
final String cancelUrl, final String locale, final String localizedLineItemName) throws IOException {
|
||||
|
||||
final CreatePayPalOneTimePaymentInput input = buildCreatePayPalOneTimePaymentInput(amount, currency, returnUrl,
|
||||
cancelUrl, locale, localizedLineItemName);
|
||||
final CreatePayPalOneTimePaymentMutation mutation = new CreatePayPalOneTimePaymentMutation(input);
|
||||
final HttpRequest request = buildRequest(mutation);
|
||||
|
||||
return httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString())
|
||||
.thenApply(httpResponse ->
|
||||
{
|
||||
// IntelliJ users: type parameters error “no instance of type variable exists so that Data conforms to Data”
|
||||
// is not accurate; this might be fixed in Kotlin 1.8: https://youtrack.jetbrains.com/issue/KTIJ-21905/
|
||||
final ApolloResponse<CreatePayPalOneTimePaymentMutation.Data> apolloResponse =
|
||||
extractApolloResponse(httpResponse, mutation);
|
||||
final CreatePayPalOneTimePaymentMutation.Data data = assertSuccessAndExtractDataFromApolloResponse(apolloResponse);
|
||||
if (data.createPayPalOneTimePayment == null) {
|
||||
logger.warn(
|
||||
"createPayPalOneTimePayment requestId={} currency={} amount={} did not have any errors but data was null. response={}",
|
||||
apolloResponse.extensions.getOrDefault("requestId", "<No-Request-Id>"),
|
||||
currency, amount, httpResponse.body());
|
||||
throw new ServiceUnavailableException();
|
||||
}
|
||||
return data.createPayPalOneTimePayment;
|
||||
});
|
||||
final HttpResponse<String> httpResponse = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
final ApolloResponse<CreatePayPalOneTimePaymentMutation.Data> apolloResponse =
|
||||
extractApolloResponse(httpResponse, mutation);
|
||||
final CreatePayPalOneTimePaymentMutation.Data data = assertSuccessAndExtractDataFromApolloResponse(apolloResponse);
|
||||
if (data.createPayPalOneTimePayment == null) {
|
||||
logger.warn(
|
||||
"createPayPalOneTimePayment requestId={} currency={} amount={} did not have any errors but data was null. response={}",
|
||||
apolloResponse.extensions.getOrDefault("requestId", "<No-Request-Id>"),
|
||||
currency, amount, httpResponse.body());
|
||||
throw new IOException();
|
||||
}
|
||||
return data.createPayPalOneTimePayment;
|
||||
|
||||
}
|
||||
|
||||
private static CreatePayPalOneTimePaymentInput buildCreatePayPalOneTimePaymentInput(BigDecimal amount,
|
||||
String currency, String returnUrl, String cancelUrl, String locale, String localizedLineItemName) {
|
||||
private static CreatePayPalOneTimePaymentInput buildCreatePayPalOneTimePaymentInput(final BigDecimal amount,
|
||||
final String currency, final String returnUrl, final String cancelUrl, final String locale, final String localizedLineItemName) {
|
||||
|
||||
// Note locale and localizedLineItemName are a best-effort, and it's possible that they will not match.
|
||||
// We could try to align with the locales PayPal documents <https://developer.paypal.com/reference/locale-codes/#supported-locale-codes>
|
||||
@@ -148,8 +143,8 @@ class BraintreeGraphqlClient {
|
||||
);
|
||||
}
|
||||
|
||||
CompletableFuture<TokenizePayPalOneTimePaymentMutation.TokenizePayPalOneTimePayment> tokenizePayPalOneTimePayment(
|
||||
final String payerId, final String paymentId, final String paymentToken) {
|
||||
TokenizePayPalOneTimePaymentMutation.TokenizePayPalOneTimePayment tokenizePayPalOneTimePayment(
|
||||
final String payerId, final String paymentId, final String paymentToken) throws IOException {
|
||||
|
||||
final TokenizePayPalOneTimePaymentInput input = new TokenizePayPalOneTimePaymentInput(
|
||||
Optional.absent(),
|
||||
@@ -159,18 +154,15 @@ class BraintreeGraphqlClient {
|
||||
|
||||
final TokenizePayPalOneTimePaymentMutation mutation = new TokenizePayPalOneTimePaymentMutation(input);
|
||||
final HttpRequest request = buildRequest(mutation);
|
||||
final HttpResponse<String> httpResponse = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
return httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString())
|
||||
.thenApply(httpResponse -> {
|
||||
// IntelliJ users: type parameters error “no instance of type variable exists so that Data conforms to Data”
|
||||
// is not accurate; this might be fixed in Kotlin 1.8: https://youtrack.jetbrains.com/issue/KTIJ-21905/
|
||||
final TokenizePayPalOneTimePaymentMutation.Data data = assertSuccessAndExtractData(httpResponse, mutation);
|
||||
return data.tokenizePayPalOneTimePayment;
|
||||
});
|
||||
final TokenizePayPalOneTimePaymentMutation.Data data = assertSuccessAndExtractData(httpResponse, mutation);
|
||||
return data.tokenizePayPalOneTimePayment;
|
||||
}
|
||||
|
||||
CompletableFuture<ChargePayPalOneTimePaymentMutation.ChargePaymentMethod> chargeOneTimePayment(
|
||||
final String paymentMethodId, final BigDecimal amount, final String merchantAccount, final long level) {
|
||||
ChargePayPalOneTimePaymentMutation.ChargePaymentMethod chargeOneTimePayment(
|
||||
final String paymentMethodId, final BigDecimal amount, final String merchantAccount, final long level)
|
||||
throws IOException {
|
||||
|
||||
final List<CustomFieldInput> customFields = List.of(
|
||||
new CustomFieldInput("level", Optional.present(Long.toString(level))));
|
||||
@@ -180,18 +172,14 @@ class BraintreeGraphqlClient {
|
||||
final ChargePayPalOneTimePaymentMutation mutation = new ChargePayPalOneTimePaymentMutation(input);
|
||||
final HttpRequest request = buildRequest(mutation);
|
||||
|
||||
return httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString())
|
||||
.thenApply(httpResponse -> {
|
||||
// IntelliJ users: type parameters error “no instance of type variable exists so that Data conforms to Data”
|
||||
// is not accurate; this might be fixed in Kotlin 1.8: https://youtrack.jetbrains.com/issue/KTIJ-21905/
|
||||
final ChargePayPalOneTimePaymentMutation.Data data = assertSuccessAndExtractData(httpResponse,
|
||||
mutation);
|
||||
return data.chargePaymentMethod;
|
||||
});
|
||||
final HttpResponse<String> httpResponse = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
final ChargePayPalOneTimePaymentMutation.Data data = assertSuccessAndExtractData(httpResponse,
|
||||
mutation);
|
||||
return data.chargePaymentMethod;
|
||||
}
|
||||
|
||||
private static ChargePaymentMethodInput buildChargePaymentMethodInput(String paymentMethodId, BigDecimal amount,
|
||||
String merchantAccount, List<CustomFieldInput> customFields) {
|
||||
private static ChargePaymentMethodInput buildChargePaymentMethodInput(final String paymentMethodId, final BigDecimal amount,
|
||||
final String merchantAccount, final List<CustomFieldInput> customFields) {
|
||||
|
||||
return new ChargePaymentMethodInput(
|
||||
Optional.absent(),
|
||||
@@ -221,25 +209,21 @@ class BraintreeGraphqlClient {
|
||||
);
|
||||
}
|
||||
|
||||
public CompletableFuture<CreatePayPalBillingAgreementMutation.CreatePayPalBillingAgreement> createPayPalBillingAgreement(
|
||||
final String returnUrl, final String cancelUrl, final String locale) {
|
||||
public CreatePayPalBillingAgreementMutation.CreatePayPalBillingAgreement createPayPalBillingAgreement(
|
||||
final String returnUrl, final String cancelUrl, final String locale) throws IOException {
|
||||
|
||||
final CreatePayPalBillingAgreementInput input = buildCreatePayPalBillingAgreementInput(returnUrl, cancelUrl,
|
||||
locale);
|
||||
final CreatePayPalBillingAgreementMutation mutation = new CreatePayPalBillingAgreementMutation(input);
|
||||
final HttpRequest request = buildRequest(mutation);
|
||||
|
||||
return httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString())
|
||||
.thenApply(httpResponse -> {
|
||||
// IntelliJ users: type parameters error “no instance of type variable exists so that Data conforms to Data”
|
||||
// is not accurate; this might be fixed in Kotlin 1.8: https://youtrack.jetbrains.com/issue/KTIJ-21905/
|
||||
final CreatePayPalBillingAgreementMutation.Data data = assertSuccessAndExtractData(httpResponse, mutation);
|
||||
return data.createPayPalBillingAgreement;
|
||||
});
|
||||
final HttpResponse<String> httpResponse = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
final CreatePayPalBillingAgreementMutation.Data data = assertSuccessAndExtractData(httpResponse, mutation);
|
||||
return data.createPayPalBillingAgreement;
|
||||
}
|
||||
|
||||
private static CreatePayPalBillingAgreementInput buildCreatePayPalBillingAgreementInput(String returnUrl,
|
||||
String cancelUrl, String locale) {
|
||||
private static CreatePayPalBillingAgreementInput buildCreatePayPalBillingAgreementInput(final String returnUrl,
|
||||
final String cancelUrl, final String locale) {
|
||||
|
||||
return new CreatePayPalBillingAgreementInput(
|
||||
Optional.absent(),
|
||||
@@ -263,8 +247,8 @@ class BraintreeGraphqlClient {
|
||||
);
|
||||
}
|
||||
|
||||
public CompletableFuture<TokenizePayPalBillingAgreementMutation.TokenizePayPalBillingAgreement> tokenizePayPalBillingAgreement(
|
||||
final String billingAgreementToken) {
|
||||
public TokenizePayPalBillingAgreementMutation.TokenizePayPalBillingAgreement tokenizePayPalBillingAgreement(
|
||||
final String billingAgreementToken) throws IOException {
|
||||
|
||||
final TokenizePayPalBillingAgreementInput input = new TokenizePayPalBillingAgreementInput(
|
||||
Optional.absent(),
|
||||
@@ -272,32 +256,24 @@ class BraintreeGraphqlClient {
|
||||
final TokenizePayPalBillingAgreementMutation mutation = new TokenizePayPalBillingAgreementMutation(input);
|
||||
final HttpRequest request = buildRequest(mutation);
|
||||
|
||||
return httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString())
|
||||
.thenApply(httpResponse -> {
|
||||
// IntelliJ users: type parameters error “no instance of type variable exists so that Data conforms to Data”
|
||||
// is not accurate; this might be fixed in Kotlin 1.8: https://youtrack.jetbrains.com/issue/KTIJ-21905/
|
||||
final TokenizePayPalBillingAgreementMutation.Data data = assertSuccessAndExtractData(httpResponse, mutation);
|
||||
return data.tokenizePayPalBillingAgreement;
|
||||
});
|
||||
final HttpResponse<String> httpResponse = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
final TokenizePayPalBillingAgreementMutation.Data data = assertSuccessAndExtractData(httpResponse, mutation);
|
||||
return data.tokenizePayPalBillingAgreement;
|
||||
}
|
||||
|
||||
public CompletableFuture<VaultPaymentMethodMutation.VaultPaymentMethod> vaultPaymentMethod(final String customerId,
|
||||
final String paymentMethodId) {
|
||||
public VaultPaymentMethodMutation.VaultPaymentMethod vaultPaymentMethod(final String customerId,
|
||||
final String paymentMethodId) throws IOException {
|
||||
|
||||
final VaultPaymentMethodInput input = buildVaultPaymentMethodInput(customerId, paymentMethodId);
|
||||
final VaultPaymentMethodMutation mutation = new VaultPaymentMethodMutation(input);
|
||||
final HttpRequest request = buildRequest(mutation);
|
||||
|
||||
return httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString())
|
||||
.thenApply(httpResponse -> {
|
||||
// IntelliJ users: type parameters error “no instance of type variable exists so that Data conforms to Data”
|
||||
// is not accurate; this might be fixed in Kotlin 1.8: https://youtrack.jetbrains.com/issue/KTIJ-21905/
|
||||
final VaultPaymentMethodMutation.Data data = assertSuccessAndExtractData(httpResponse, mutation);
|
||||
return data.vaultPaymentMethod;
|
||||
});
|
||||
final HttpResponse<String> httpResponse = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
final VaultPaymentMethodMutation.Data data = assertSuccessAndExtractData(httpResponse, mutation);
|
||||
return data.vaultPaymentMethod;
|
||||
}
|
||||
|
||||
private static VaultPaymentMethodInput buildVaultPaymentMethodInput(String customerId, String paymentMethodId) {
|
||||
private static VaultPaymentMethodInput buildVaultPaymentMethodInput(final String customerId, final String paymentMethodId) {
|
||||
return new VaultPaymentMethodInput(
|
||||
Optional.absent(),
|
||||
paymentMethodId,
|
||||
@@ -311,26 +287,28 @@ class BraintreeGraphqlClient {
|
||||
|
||||
/**
|
||||
* Verifies that the HTTP response has a {@code 200} status code and the GraphQL response has no errors, otherwise
|
||||
* throws a {@link ServiceUnavailableException}.
|
||||
* throws a {@link IOException}.
|
||||
*/
|
||||
private static <T extends Operation<U>, U extends Operation.Data> U assertSuccessAndExtractData(
|
||||
HttpResponse<String> httpResponse, T operation) {
|
||||
final HttpResponse<String> httpResponse, final T operation) throws IOException {
|
||||
return assertSuccessAndExtractDataFromApolloResponse(extractApolloResponse(httpResponse, operation));
|
||||
}
|
||||
|
||||
private static <T extends Operation<U>, U extends Operation.Data> ApolloResponse<U> extractApolloResponse(
|
||||
HttpResponse<String> httpResponse, T operation) {
|
||||
final HttpResponse<String> httpResponse, final T operation) throws IOException {
|
||||
|
||||
if (httpResponse.statusCode() != 200) {
|
||||
logger.warn("Received HTTP response status {} ({})", httpResponse.statusCode(),
|
||||
httpResponse.headers().firstValue("paypal-debug-id").orElse("<debug id absent>"));
|
||||
throw new ServiceUnavailableException();
|
||||
throw new IOException();
|
||||
}
|
||||
|
||||
return Operations.parseJsonResponse(operation, httpResponse.body());
|
||||
}
|
||||
|
||||
private static <T extends Operation<U>, U extends Operation.Data> U assertSuccessAndExtractDataFromApolloResponse(final ApolloResponse<U> response) {
|
||||
private static <T extends Operation<U>, U extends Operation.Data> U assertSuccessAndExtractDataFromApolloResponse(
|
||||
final ApolloResponse<U> response)
|
||||
throws IOException {
|
||||
if (response.hasErrors() || response.data == null) {
|
||||
//noinspection ConstantConditions
|
||||
response.errors.forEach(
|
||||
@@ -342,7 +320,7 @@ class BraintreeGraphqlClient {
|
||||
response.operation.name(), error.getMessage(), legacyCode);
|
||||
});
|
||||
|
||||
throw new ServiceUnavailableException();
|
||||
throw new IOException();
|
||||
}
|
||||
|
||||
return response.data;
|
||||
|
||||
+114
-113
@@ -5,7 +5,11 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
|
||||
import com.braintree.graphql.clientoperation.ChargePayPalOneTimePaymentMutation;
|
||||
import com.braintree.graphql.clientoperation.CreatePayPalBillingAgreementMutation;
|
||||
import com.braintree.graphql.clientoperation.CreatePayPalOneTimePaymentMutation;
|
||||
import com.braintree.graphql.clientoperation.TokenizePayPalBillingAgreementMutation;
|
||||
import com.braintree.graphql.clientoperation.TokenizePayPalOneTimePaymentMutation;
|
||||
import com.braintree.graphql.clientoperation.VaultPaymentMethodMutation;
|
||||
import com.braintreegateway.BraintreeGateway;
|
||||
import com.braintreegateway.ClientTokenRequest;
|
||||
@@ -36,7 +40,6 @@ import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Executor;
|
||||
import javax.annotation.Nullable;
|
||||
import org.slf4j.Logger;
|
||||
@@ -45,7 +48,6 @@ import org.whispersystems.textsecuregcm.currency.CurrencyConversionManager;
|
||||
import org.whispersystems.textsecuregcm.http.FaultTolerantHttpClient;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.PaymentTime;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.util.ExecutorUtil;
|
||||
import org.whispersystems.textsecuregcm.util.GoogleApiUtil;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
@@ -128,92 +130,88 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
|
||||
return paymentMethod == PaymentMethod.PAYPAL;
|
||||
}
|
||||
|
||||
public CompletableFuture<Optional<PaymentDetails>> getPaymentDetails(final String paymentId) {
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
try {
|
||||
final Transaction transaction = braintreeGateway.transaction().find(paymentId);
|
||||
ChargeFailure chargeFailure = null;
|
||||
if (!getPaymentStatus(transaction.getStatus()).equals(PaymentStatus.SUCCEEDED)) {
|
||||
chargeFailure = createChargeFailure(transaction);
|
||||
}
|
||||
return Optional.of(new PaymentDetails(transaction.getGraphQLId(),
|
||||
transaction.getCustomFields(),
|
||||
getPaymentStatus(transaction.getStatus()),
|
||||
transaction.getCreatedAt().toInstant(),
|
||||
chargeFailure));
|
||||
|
||||
} catch (final NotFoundException e) {
|
||||
return Optional.empty();
|
||||
public Optional<PaymentDetails> getPaymentDetails(final String paymentId) {
|
||||
try {
|
||||
final Transaction transaction = braintreeGateway.transaction().find(paymentId);
|
||||
ChargeFailure chargeFailure = null;
|
||||
if (!getPaymentStatus(transaction.getStatus()).equals(PaymentStatus.SUCCEEDED)) {
|
||||
chargeFailure = createChargeFailure(transaction);
|
||||
}
|
||||
}, executor);
|
||||
return Optional.of(new PaymentDetails(transaction.getGraphQLId(),
|
||||
transaction.getCustomFields(),
|
||||
getPaymentStatus(transaction.getStatus()),
|
||||
transaction.getCreatedAt().toInstant(),
|
||||
chargeFailure));
|
||||
|
||||
} catch (final NotFoundException e) {
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
public CompletableFuture<PayPalOneTimePaymentApprovalDetails> createOneTimePayment(String currency, long amount,
|
||||
String locale, String returnUrl, String cancelUrl, String localizedLineItemname) {
|
||||
return braintreeGraphqlClient.createPayPalOneTimePayment(convertApiAmountToBraintreeAmount(currency, amount),
|
||||
currency.toUpperCase(Locale.ROOT), returnUrl,
|
||||
cancelUrl, locale, localizedLineItemname)
|
||||
.thenApply(result -> new PayPalOneTimePaymentApprovalDetails((String) result.approvalUrl, result.paymentId));
|
||||
public PayPalOneTimePaymentApprovalDetails createOneTimePayment(final String currency, final long amount,
|
||||
final String locale, final String returnUrl, final String cancelUrl, final String localizedLineItemName) throws IOException {
|
||||
final CreatePayPalOneTimePaymentMutation.CreatePayPalOneTimePayment result = braintreeGraphqlClient.createPayPalOneTimePayment(
|
||||
convertApiAmountToBraintreeAmount(currency, amount),
|
||||
currency.toUpperCase(Locale.ROOT), returnUrl,
|
||||
cancelUrl, locale, localizedLineItemName);
|
||||
return new PayPalOneTimePaymentApprovalDetails((String) result.approvalUrl, result.paymentId);
|
||||
}
|
||||
|
||||
public CompletableFuture<PayPalChargeSuccessDetails> captureOneTimePayment(String payerId, String paymentId,
|
||||
String paymentToken, String currency, long amount, long level, @Nullable ClientPlatform clientPlatform) {
|
||||
return braintreeGraphqlClient.tokenizePayPalOneTimePayment(payerId, paymentId, paymentToken)
|
||||
.thenCompose(response -> braintreeGraphqlClient.chargeOneTimePayment(
|
||||
response.paymentMethod.id,
|
||||
convertApiAmountToBraintreeAmount(currency, amount),
|
||||
currenciesToMerchantAccounts.get(currency.toLowerCase(Locale.ROOT)),
|
||||
level)
|
||||
.thenComposeAsync(chargeResponse -> {
|
||||
public PayPalChargeSuccessDetails captureOneTimePayment(final String payerId, final String paymentId,
|
||||
final String paymentToken, final String currency, final long amount, final long level, @Nullable final ClientPlatform clientPlatform)
|
||||
throws SubscriptionProcessorException, IOException {
|
||||
final TokenizePayPalOneTimePaymentMutation.TokenizePayPalOneTimePayment response = braintreeGraphqlClient.tokenizePayPalOneTimePayment(
|
||||
payerId, paymentId, paymentToken);
|
||||
final ChargePayPalOneTimePaymentMutation.ChargePaymentMethod chargeResponse = braintreeGraphqlClient.chargeOneTimePayment(
|
||||
response.paymentMethod.id,
|
||||
convertApiAmountToBraintreeAmount(currency, amount),
|
||||
currenciesToMerchantAccounts.get(currency.toLowerCase(Locale.ROOT)),
|
||||
level);
|
||||
|
||||
final PaymentStatus paymentStatus = getPaymentStatus(chargeResponse.transaction.status);
|
||||
if (paymentStatus == PaymentStatus.SUCCEEDED || paymentStatus == PaymentStatus.PROCESSING) {
|
||||
publishDonationEvent(amount, currency, Instant.now(), clientPlatform);
|
||||
return CompletableFuture.completedFuture(new PayPalChargeSuccessDetails(chargeResponse.transaction.id));
|
||||
}
|
||||
final PaymentStatus paymentStatus = getPaymentStatus(chargeResponse.transaction.status);
|
||||
if (paymentStatus == PaymentStatus.SUCCEEDED || paymentStatus == PaymentStatus.PROCESSING) {
|
||||
publishDonationEvent(amount, currency, Instant.now(), clientPlatform);
|
||||
return new PayPalChargeSuccessDetails(chargeResponse.transaction.id);
|
||||
}
|
||||
|
||||
// the GraphQL/Apollo interfaces are a tad unwieldy for this type of status checking
|
||||
final Transaction unsuccessfulTx = braintreeGateway.transaction().find(chargeResponse.transaction.id);
|
||||
// the GraphQL/Apollo interfaces are a tad unwieldy for this type of status checking
|
||||
final Transaction unsuccessfulTx = braintreeGateway.transaction().find(chargeResponse.transaction.id);
|
||||
|
||||
if (PAYPAL_PAYMENT_ALREADY_COMPLETED_PROCESSOR_CODE.equals(unsuccessfulTx.getProcessorResponseCode())
|
||||
|| Transaction.GatewayRejectionReason.DUPLICATE.equals(unsuccessfulTx.getGatewayRejectionReason())) {
|
||||
// the payment has already been charged - maybe a previous call timed out or was interrupted -
|
||||
// in any case, check for a successful transaction with the paymentId
|
||||
final ResourceCollection<Transaction> search = braintreeGateway.transaction()
|
||||
.search(new TransactionSearchRequest()
|
||||
.paypalPaymentId().is(paymentId)
|
||||
.status().in(
|
||||
Transaction.Status.SETTLED,
|
||||
Transaction.Status.SETTLING,
|
||||
Transaction.Status.SUBMITTED_FOR_SETTLEMENT,
|
||||
Transaction.Status.SETTLEMENT_PENDING
|
||||
)
|
||||
);
|
||||
if (PAYPAL_PAYMENT_ALREADY_COMPLETED_PROCESSOR_CODE.equals(unsuccessfulTx.getProcessorResponseCode())
|
||||
|| Transaction.GatewayRejectionReason.DUPLICATE.equals(unsuccessfulTx.getGatewayRejectionReason())) {
|
||||
// the payment has already been charged - maybe a previous call timed out or was interrupted -
|
||||
// in any case, check for a successful transaction with the paymentId
|
||||
final ResourceCollection<Transaction> search = braintreeGateway.transaction()
|
||||
.search(new TransactionSearchRequest()
|
||||
.paypalPaymentId().is(paymentId)
|
||||
.status().in(
|
||||
Transaction.Status.SETTLED,
|
||||
Transaction.Status.SETTLING,
|
||||
Transaction.Status.SUBMITTED_FOR_SETTLEMENT,
|
||||
Transaction.Status.SETTLEMENT_PENDING
|
||||
)
|
||||
);
|
||||
|
||||
if (search.getMaximumSize() == 0) {
|
||||
return CompletableFuture.failedFuture(ExceptionUtils.wrap(new IOException()));
|
||||
}
|
||||
if (search.getMaximumSize() == 0) {
|
||||
throw new IOException();
|
||||
}
|
||||
|
||||
final Transaction successfulTx = search.getFirst();
|
||||
final Transaction successfulTx = search.getFirst();
|
||||
|
||||
publishDonationEvent(amount, currency, successfulTx.getCreatedAt().toInstant(), clientPlatform);
|
||||
publishDonationEvent(amount, currency, successfulTx.getCreatedAt().toInstant(), clientPlatform);
|
||||
|
||||
return CompletableFuture.completedFuture(
|
||||
new PayPalChargeSuccessDetails(successfulTx.getGraphQLId()));
|
||||
}
|
||||
return new PayPalChargeSuccessDetails(successfulTx.getGraphQLId());
|
||||
}
|
||||
|
||||
return switch (unsuccessfulTx.getProcessorResponseCode()) {
|
||||
case GENERIC_DECLINED_PROCESSOR_CODE, PAYPAL_FUNDING_INSTRUMENT_DECLINED_PROCESSOR_CODE ->
|
||||
CompletableFuture.failedFuture(
|
||||
new SubscriptionProcessorException(getProvider(), createChargeFailure(unsuccessfulTx)));
|
||||
switch (unsuccessfulTx.getProcessorResponseCode()) {
|
||||
case GENERIC_DECLINED_PROCESSOR_CODE, PAYPAL_FUNDING_INSTRUMENT_DECLINED_PROCESSOR_CODE ->
|
||||
throw new SubscriptionProcessorException(getProvider(), createChargeFailure(unsuccessfulTx));
|
||||
|
||||
default -> {
|
||||
logger.info("PayPal charge unexpectedly failed: {}", unsuccessfulTx.getProcessorResponseCode());
|
||||
|
||||
yield CompletableFuture.failedFuture(ExceptionUtils.wrap(new IOException()));
|
||||
}
|
||||
};
|
||||
}, executor));
|
||||
default -> {
|
||||
logger.info("PayPal charge unexpectedly failed: {}", unsuccessfulTx.getProcessorResponseCode());
|
||||
throw new IOException();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void publishDonationEvent(final long amount,
|
||||
@@ -264,7 +262,7 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
|
||||
return amount.multiply(ONE_MILLION).longValueExact();
|
||||
}
|
||||
|
||||
private static PaymentStatus getPaymentStatus(Transaction.Status status) {
|
||||
private static PaymentStatus getPaymentStatus(final Transaction.Status status) {
|
||||
return switch (status) {
|
||||
case SETTLEMENT_CONFIRMED, SETTLING, SUBMITTED_FOR_SETTLEMENT, SETTLED -> PaymentStatus.SUCCEEDED;
|
||||
case AUTHORIZATION_EXPIRED, GATEWAY_REJECTED, PROCESSOR_DECLINED, SETTLEMENT_DECLINED, VOIDED, FAILED ->
|
||||
@@ -273,9 +271,9 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
|
||||
};
|
||||
}
|
||||
|
||||
private static PaymentStatus getPaymentStatus(com.braintree.graphql.client.type.PaymentStatus status) {
|
||||
private static PaymentStatus getPaymentStatus(final com.braintree.graphql.client.type.PaymentStatus status) {
|
||||
try {
|
||||
Transaction.Status transactionStatus = Transaction.Status.valueOf(status.rawValue);
|
||||
final Transaction.Status transactionStatus = Transaction.Status.valueOf(status.rawValue);
|
||||
|
||||
return getPaymentStatus(transactionStatus);
|
||||
} catch (final Exception e) {
|
||||
@@ -283,7 +281,8 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
|
||||
}
|
||||
}
|
||||
|
||||
private static SubscriptionStatus getSubscriptionStatus(final Subscription.Status status, final boolean latestTransactionFailed) {
|
||||
private static SubscriptionStatus getSubscriptionStatus(final Subscription.Status status,
|
||||
final boolean latestTransactionFailed) {
|
||||
return switch (status) {
|
||||
// Stripe returns a PAST_DUE status if the subscription's most recent payment failed.
|
||||
// This check ensures that Braintree is consistent with Stripe.
|
||||
@@ -316,7 +315,7 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
|
||||
|
||||
@Override
|
||||
public ProcessorCustomer createCustomer(final byte[] subscriberUser, @Nullable final ClientPlatform clientPlatform) {
|
||||
CustomerRequest request = new CustomerRequest()
|
||||
final CustomerRequest request = new CustomerRequest()
|
||||
.customField("subscriber_user", HexFormat.of().formatHex(subscriberUser));
|
||||
|
||||
if (clientPlatform != null) {
|
||||
@@ -332,19 +331,19 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
|
||||
|
||||
@Override
|
||||
public String createPaymentMethodSetupToken(final String customerId) {
|
||||
ClientTokenRequest request = new ClientTokenRequest().customerId(customerId);
|
||||
final ClientTokenRequest request = new ClientTokenRequest().customerId(customerId);
|
||||
|
||||
return braintreeGateway.clientToken().generate(request);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setDefaultPaymentMethodForCustomer(String customerId, String billingAgreementToken,
|
||||
@Nullable String currentSubscriptionId) {
|
||||
public void setDefaultPaymentMethodForCustomer(final String customerId, final String billingAgreementToken,
|
||||
@Nullable final String currentSubscriptionId) throws IOException {
|
||||
final Optional<String> maybeSubscriptionId = Optional.ofNullable(currentSubscriptionId);
|
||||
final TokenizePayPalBillingAgreementMutation.TokenizePayPalBillingAgreement tokenizePayPalBillingAgreement =
|
||||
braintreeGraphqlClient.tokenizePayPalBillingAgreement(billingAgreementToken).join();
|
||||
braintreeGraphqlClient.tokenizePayPalBillingAgreement(billingAgreementToken);
|
||||
final VaultPaymentMethodMutation.VaultPaymentMethod vaultPaymentMethod =
|
||||
braintreeGraphqlClient.vaultPaymentMethod(customerId, tokenizePayPalBillingAgreement.paymentMethod.id).join();
|
||||
braintreeGraphqlClient.vaultPaymentMethod(customerId, tokenizePayPalBillingAgreement.paymentMethod.id);
|
||||
final Result<Customer> result = braintreeGateway.customer()
|
||||
.update(customerId, new CustomerRequest().defaultPaymentMethodToken(vaultPaymentMethod.paymentMethod.id));
|
||||
maybeSubscriptionId.ifPresent(subscriptionId ->
|
||||
@@ -353,13 +352,13 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getSubscription(String subscriptionId) {
|
||||
public Object getSubscription(final String subscriptionId) {
|
||||
return braintreeGateway.subscription().find(subscriptionId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public SubscriptionId createSubscription(String customerId, String planId, long level,
|
||||
long lastSubscriptionCreatedAt)
|
||||
public SubscriptionId createSubscription(final String customerId, final String planId, final long level,
|
||||
final long lastSubscriptionCreatedAt)
|
||||
throws SubscriptionProcessorConflictException, SubscriptionProcessorException {
|
||||
|
||||
final com.braintreegateway.PaymentMethod paymentMethod = getDefaultPaymentMethod(customerId);
|
||||
@@ -406,14 +405,15 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
|
||||
return new SubscriptionId(result.getTarget().getId());
|
||||
}
|
||||
|
||||
private com.braintreegateway.PaymentMethod getDefaultPaymentMethod(String customerId) {
|
||||
private com.braintreegateway.PaymentMethod getDefaultPaymentMethod(final String customerId) {
|
||||
return braintreeGateway.customer().find(customerId).getDefaultPaymentMethod();
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public CustomerAwareSubscriptionPaymentProcessor.SubscriptionId updateSubscription(Object subscriptionObj, String planId, long level,
|
||||
String idempotencyKey) throws SubscriptionProcessorConflictException, SubscriptionProcessorException {
|
||||
public CustomerAwareSubscriptionPaymentProcessor.SubscriptionId updateSubscription(final Object subscriptionObj,
|
||||
final String planId, final long level,
|
||||
final String idempotencyKey) throws SubscriptionProcessorConflictException, SubscriptionProcessorException {
|
||||
|
||||
if (!(subscriptionObj instanceof final Subscription subscription)) {
|
||||
throw new IllegalArgumentException("invalid subscription object: " + subscriptionObj.getClass().getName());
|
||||
@@ -425,7 +425,7 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
|
||||
endSubscription(subscription);
|
||||
|
||||
final Transaction transaction = getLatestTransactionForSubscription(subscription)
|
||||
.orElseThrow(() -> ExceptionUtils.wrap(new SubscriptionProcessorConflictException()));
|
||||
.orElseThrow(SubscriptionProcessorConflictException::new);
|
||||
|
||||
final Customer customer = transaction.getCustomer();
|
||||
|
||||
@@ -434,13 +434,13 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
|
||||
}
|
||||
|
||||
@Override
|
||||
public LevelAndCurrency getLevelAndCurrencyForSubscription(Object subscriptionObj) {
|
||||
public LevelAndCurrency getLevelAndCurrencyForSubscription(final Object subscriptionObj) {
|
||||
final Subscription subscription = getSubscription(subscriptionObj);
|
||||
final Plan plan = findPlan(subscription.getPlanId());
|
||||
return new LevelAndCurrency(getLevelForPlan(plan), plan.getCurrencyIsoCode().toLowerCase(Locale.ROOT));
|
||||
}
|
||||
|
||||
private Plan findPlan(String planId) {
|
||||
private Plan findPlan(final String planId) {
|
||||
return braintreeGateway.plan().find(planId);
|
||||
}
|
||||
|
||||
@@ -449,7 +449,7 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
|
||||
try {
|
||||
metadata = SystemMapper.jsonMapper().readValue(plan.getDescription(), BraintreePlanMetadata.class);
|
||||
|
||||
} catch (JsonProcessingException e) {
|
||||
} catch (final JsonProcessingException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
@@ -458,7 +458,7 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
|
||||
|
||||
@Override
|
||||
public SubscriptionInformation getSubscriptionInformation(final String subscriptionId) {
|
||||
final Subscription subscription = getSubscription(getSubscription(subscriptionId));
|
||||
final Subscription subscription = getSubscription(getSubscription(subscriptionId));
|
||||
final Plan plan = braintreeGateway.plan().find(subscription.getPlanId());
|
||||
final long level = getLevelForPlan(plan);
|
||||
|
||||
@@ -500,11 +500,12 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
|
||||
return new TransactionInfo(paymentMethod, paymentProcessing, false, null);
|
||||
}
|
||||
|
||||
private PaymentMethod getPaymentMethodFromTransaction(Transaction transaction) {
|
||||
private PaymentMethod getPaymentMethodFromTransaction(final Transaction transaction) {
|
||||
if (transaction.getPayPalDetails() != null) {
|
||||
return PaymentMethod.PAYPAL;
|
||||
}
|
||||
logger.error("Unexpected payment method from Braintree: {}, transaction id {}", transaction.getPaymentInstrumentType(), transaction.getId());
|
||||
logger.error("Unexpected payment method from Braintree: {}, transaction id {}",
|
||||
transaction.getPaymentInstrumentType(), transaction.getId());
|
||||
return PaymentMethod.UNKNOWN;
|
||||
}
|
||||
|
||||
@@ -512,7 +513,7 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
|
||||
return status == Transaction.Status.SETTLEMENT_PENDING;
|
||||
}
|
||||
|
||||
private ChargeFailure createChargeFailure(Transaction transaction) {
|
||||
private ChargeFailure createChargeFailure(final Transaction transaction) {
|
||||
|
||||
final String code;
|
||||
final String message;
|
||||
@@ -539,7 +540,7 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
|
||||
}
|
||||
|
||||
@Override
|
||||
public void cancelAllActiveSubscriptions(String customerId) {
|
||||
public void cancelAllActiveSubscriptions(final String customerId) {
|
||||
final Customer customer = braintreeGateway.customer().find(customerId);
|
||||
ExecutorUtil.runAll(executor, Optional.ofNullable(customer.getDefaultPaymentMethod())
|
||||
.stream()
|
||||
@@ -548,7 +549,7 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
|
||||
.toList());
|
||||
}
|
||||
|
||||
private void endSubscription(Subscription subscription) {
|
||||
private void endSubscription(final Subscription subscription) {
|
||||
final boolean latestTransactionFailed = getLatestTransactionForSubscription(subscription)
|
||||
.map(this::getTransactionInfo)
|
||||
.map(TransactionInfo::transactionFailed)
|
||||
@@ -563,20 +564,20 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
|
||||
}
|
||||
}
|
||||
|
||||
private void cancelSubscriptionAtEndOfCurrentPeriod(Subscription subscription) {
|
||||
private void cancelSubscriptionAtEndOfCurrentPeriod(final Subscription subscription) {
|
||||
braintreeGateway
|
||||
.subscription()
|
||||
.update(subscription.getId(),
|
||||
new SubscriptionRequest().numberOfBillingCycles(subscription.getCurrentBillingCycle()));
|
||||
}
|
||||
|
||||
private void cancelSubscriptionImmediately(Subscription subscription) {
|
||||
private void cancelSubscriptionImmediately(final Subscription subscription) {
|
||||
braintreeGateway.subscription().cancel(subscription.getId());
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public ReceiptItem getReceiptItem(String subscriptionId)
|
||||
public ReceiptItem getReceiptItem(final String subscriptionId)
|
||||
throws SubscriptionReceiptRequestedForOpenPaymentException, SubscriptionChargeFailurePaymentRequiredException {
|
||||
final Subscription subscription = getSubscription(getSubscription(subscriptionId));
|
||||
final Transaction transaction = getLatestTransactionForSubscription(subscription)
|
||||
@@ -597,31 +598,31 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
|
||||
try {
|
||||
metadata = SystemMapper.jsonMapper().readValue(plan.getDescription(), BraintreePlanMetadata.class);
|
||||
|
||||
} catch (JsonProcessingException e) {
|
||||
} catch (final JsonProcessingException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
return new ReceiptItem(transaction.getId(), PaymentTime.periodStart(paidAt), metadata.level());
|
||||
}
|
||||
|
||||
private static Subscription getSubscription(Object subscriptionObj) {
|
||||
private static Subscription getSubscription(final Object subscriptionObj) {
|
||||
if (!(subscriptionObj instanceof final Subscription subscription)) {
|
||||
throw new IllegalArgumentException("Invalid subscription object: " + subscriptionObj.getClass().getName());
|
||||
}
|
||||
return subscription;
|
||||
}
|
||||
|
||||
private Optional<Transaction> getLatestTransactionForSubscription(Subscription subscription) {
|
||||
private Optional<Transaction> getLatestTransactionForSubscription(final Subscription subscription) {
|
||||
return subscription.getTransactions().stream()
|
||||
.max(Comparator.comparing(Transaction::getCreatedAt));
|
||||
.max(Comparator.comparing(Transaction::getCreatedAt));
|
||||
}
|
||||
|
||||
public CompletableFuture<PayPalBillingAgreementApprovalDetails> createPayPalBillingAgreement(final String returnUrl,
|
||||
final String cancelUrl, final String locale) {
|
||||
return braintreeGraphqlClient.createPayPalBillingAgreement(returnUrl, cancelUrl, locale)
|
||||
.thenApply(response ->
|
||||
new PayPalBillingAgreementApprovalDetails((String) response.approvalUrl, response.billingAgreementToken)
|
||||
);
|
||||
public PayPalBillingAgreementApprovalDetails createPayPalBillingAgreement(final String returnUrl,
|
||||
final String cancelUrl, final String locale)
|
||||
throws IOException {
|
||||
final CreatePayPalBillingAgreementMutation.CreatePayPalBillingAgreement response = braintreeGraphqlClient.createPayPalBillingAgreement(
|
||||
returnUrl, cancelUrl, locale);
|
||||
return new PayPalBillingAgreementApprovalDetails((String) response.approvalUrl, response.billingAgreementToken);
|
||||
}
|
||||
|
||||
public record PayPalBillingAgreementApprovalDetails(String approvalUrl, String billingAgreementToken) {
|
||||
|
||||
+4
-2
@@ -5,6 +5,7 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Set;
|
||||
import javax.annotation.Nullable;
|
||||
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
|
||||
@@ -41,10 +42,11 @@ public interface CustomerAwareSubscriptionPaymentProcessor extends SubscriptionP
|
||||
* {@link #createPaymentMethodSetupToken}
|
||||
* @param currentSubscriptionId (nullable) an active subscription ID, in case it needs an explicit update
|
||||
* @throws SubscriptionInvalidArgumentsException If the paymentMethodToken is invalid or the payment method has not
|
||||
* finished being set up
|
||||
* finished being set up
|
||||
* @throws IOException If there was an error talking to the external payment provider
|
||||
*/
|
||||
void setDefaultPaymentMethodForCustomer(String customerId, String paymentMethodToken,
|
||||
@Nullable String currentSubscriptionId) throws SubscriptionInvalidArgumentsException;
|
||||
@Nullable String currentSubscriptionId) throws SubscriptionInvalidArgumentsException, IOException;
|
||||
|
||||
Object getSubscription(String subscriptionId);
|
||||
|
||||
|
||||
+14
-1
@@ -24,5 +24,18 @@ public enum PaymentMethod {
|
||||
*/
|
||||
IDEAL,
|
||||
GOOGLE_PLAY_BILLING,
|
||||
APPLE_APP_STORE
|
||||
APPLE_APP_STORE;
|
||||
|
||||
|
||||
public org.signal.chat.purchase.PaymentMethod toProtoPaymentMethod() {
|
||||
return switch (this) {
|
||||
case CARD -> org.signal.chat.purchase.PaymentMethod.PAYMENT_METHOD_CARD;
|
||||
case SEPA_DEBIT -> org.signal.chat.purchase.PaymentMethod.PAYMENT_METHOD_SEPA_DEBIT;
|
||||
case IDEAL -> org.signal.chat.purchase.PaymentMethod.PAYMENT_METHOD_IDEAL;
|
||||
case PAYPAL -> org.signal.chat.purchase.PaymentMethod.PAYMENT_METHOD_PAYPAL;
|
||||
case GOOGLE_PLAY_BILLING -> org.signal.chat.purchase.PaymentMethod.PAYMENT_METHOD_GOOGLE_PLAY_BILLING;
|
||||
case APPLE_APP_STORE -> org.signal.chat.purchase.PaymentMethod.PAYMENT_METHOD_APPLE_APP_STORE;
|
||||
case UNKNOWN -> org.signal.chat.purchase.PaymentMethod.PAYMENT_METHOD_UNKNOWN;
|
||||
};
|
||||
}
|
||||
}
|
||||
+5
-5
@@ -48,12 +48,12 @@ public enum PaymentProvider {
|
||||
return id;
|
||||
}
|
||||
|
||||
public org.signal.chat.subscriptions.PaymentProvider toProto() {
|
||||
public org.signal.chat.purchase.PaymentProvider toProto() {
|
||||
return switch (this) {
|
||||
case STRIPE -> org.signal.chat.subscriptions.PaymentProvider.PAYMENT_PROVIDER_STRIPE;
|
||||
case BRAINTREE -> org.signal.chat.subscriptions.PaymentProvider.PAYMENT_PROVIDER_BRAINTREE;
|
||||
case GOOGLE_PLAY_BILLING -> org.signal.chat.subscriptions.PaymentProvider.PAYMENT_PROVIDER_GOOGLE_PLAY_BILLING;
|
||||
case APPLE_APP_STORE -> org.signal.chat.subscriptions.PaymentProvider.PAYMENT_PROVIDER_APPLE_APP_STORE;
|
||||
case STRIPE -> org.signal.chat.purchase.PaymentProvider.PAYMENT_PROVIDER_STRIPE;
|
||||
case BRAINTREE -> org.signal.chat.purchase.PaymentProvider.PAYMENT_PROVIDER_BRAINTREE;
|
||||
case GOOGLE_PLAY_BILLING -> org.signal.chat.purchase.PaymentProvider.PAYMENT_PROVIDER_GOOGLE_PLAY_BILLING;
|
||||
case APPLE_APP_STORE -> org.signal.chat.purchase.PaymentProvider.PAYMENT_PROVIDER_APPLE_APP_STORE;
|
||||
};
|
||||
}
|
||||
}
|
||||
+178
-180
@@ -62,11 +62,8 @@ import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.function.Consumer;
|
||||
import javax.annotation.Nonnull;
|
||||
import javax.annotation.Nullable;
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
@@ -76,11 +73,11 @@ import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.WhisperServerVersion;
|
||||
import org.whispersystems.textsecuregcm.storage.PaymentTime;
|
||||
import org.whispersystems.textsecuregcm.util.Conversions;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.util.ExecutorUtil;
|
||||
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
|
||||
|
||||
public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(StripeManager.class);
|
||||
private static final String METADATA_KEY_LEVEL = "level";
|
||||
private static final String METADATA_KEY_CLIENT_PLATFORM = "clientPlatform";
|
||||
@@ -93,11 +90,11 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
|
||||
@VisibleForTesting
|
||||
StripeManager(
|
||||
@Nonnull StripeClient stripeClient,
|
||||
@Nonnull Executor executor,
|
||||
@Nonnull byte[] idempotencyKeyGenerator,
|
||||
@Nonnull String boostDescription,
|
||||
@Nonnull Map<PaymentMethod, Set<String>> supportedCurrenciesByPaymentMethod) {
|
||||
final StripeClient stripeClient,
|
||||
final Executor executor,
|
||||
final byte[] idempotencyKeyGenerator,
|
||||
final String boostDescription,
|
||||
final Map<PaymentMethod, Set<String>> supportedCurrenciesByPaymentMethod) {
|
||||
Stripe.setAppInfo("Signal-Server", WhisperServerVersion.getServerVersion());
|
||||
|
||||
this.stripeClient = Objects.requireNonNull(stripeClient);
|
||||
@@ -109,13 +106,15 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
this.boostDescription = Objects.requireNonNull(boostDescription);
|
||||
this.supportedCurrenciesByPaymentMethod = supportedCurrenciesByPaymentMethod;
|
||||
}
|
||||
|
||||
public StripeManager(
|
||||
@Nonnull String apiKey,
|
||||
@Nonnull Executor executor,
|
||||
@Nonnull byte[] idempotencyKeyGenerator,
|
||||
@Nonnull String boostDescription,
|
||||
@Nonnull Map<PaymentMethod, Set<String>> supportedCurrenciesByPaymentMethod) {
|
||||
this(new StripeClient(apiKey), executor, idempotencyKeyGenerator, boostDescription, supportedCurrenciesByPaymentMethod);
|
||||
final String apiKey,
|
||||
final Executor executor,
|
||||
final byte[] idempotencyKeyGenerator,
|
||||
final String boostDescription,
|
||||
final Map<PaymentMethod, Set<String>> supportedCurrenciesByPaymentMethod) {
|
||||
this(new StripeClient(apiKey), executor, idempotencyKeyGenerator, boostDescription,
|
||||
supportedCurrenciesByPaymentMethod);
|
||||
|
||||
if (StringUtils.isEmpty(apiKey)) {
|
||||
throw new IllegalArgumentException("apiKey cannot be empty");
|
||||
@@ -128,7 +127,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supportsPaymentMethod(PaymentMethod paymentMethod) {
|
||||
public boolean supportsPaymentMethod(final PaymentMethod paymentMethod) {
|
||||
return paymentMethod == PaymentMethod.CARD
|
||||
|| paymentMethod == PaymentMethod.SEPA_DEBIT
|
||||
|| paymentMethod == PaymentMethod.IDEAL;
|
||||
@@ -138,7 +137,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
return commonOptions(null);
|
||||
}
|
||||
|
||||
private RequestOptions commonOptions(@Nullable String idempotencyKey) {
|
||||
private RequestOptions commonOptions(@Nullable final String idempotencyKey) {
|
||||
return RequestOptions.builder()
|
||||
.setIdempotencyKey(idempotencyKey)
|
||||
.build();
|
||||
@@ -157,46 +156,46 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
final Customer customer = stripeClient.v1().customers()
|
||||
.create(builder.build(), commonOptions(generateIdempotencyKeyForSubscriberUser(subscriberUser)));
|
||||
return new ProcessorCustomer(customer.getId(), getProvider());
|
||||
} catch (StripeException e) {
|
||||
} catch (final StripeException e) {
|
||||
throw new UncheckedIOException(new IOException(e));
|
||||
}
|
||||
}
|
||||
|
||||
public Customer getCustomer(String customerId) {
|
||||
CustomerRetrieveParams params = CustomerRetrieveParams.builder().build();
|
||||
public Customer getCustomer(final String customerId) {
|
||||
final CustomerRetrieveParams params = CustomerRetrieveParams.builder().build();
|
||||
try {
|
||||
return stripeClient.v1().customers().retrieve(customerId, params, commonOptions());
|
||||
} catch (StripeException e) {
|
||||
} catch (final StripeException e) {
|
||||
throw new UncheckedIOException(new IOException(e));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setDefaultPaymentMethodForCustomer(String customerId, String paymentMethodId,
|
||||
@Nullable String currentSubscriptionId) throws SubscriptionInvalidArgumentsException {
|
||||
CustomerUpdateParams params = CustomerUpdateParams.builder()
|
||||
.setInvoiceSettings(InvoiceSettings.builder()
|
||||
.setDefaultPaymentMethod(paymentMethodId)
|
||||
.build())
|
||||
.build();
|
||||
try {
|
||||
stripeClient.v1().customers().update(customerId, params, commonOptions());
|
||||
} catch (InvalidRequestException e) {
|
||||
// Could happen if the paymentMethodId was bunk or the client didn't actually finish setting it up
|
||||
throw new SubscriptionInvalidArgumentsException(e.getMessage());
|
||||
} catch (StripeException e) {
|
||||
throw new UncheckedIOException(new IOException(e));
|
||||
}
|
||||
public void setDefaultPaymentMethodForCustomer(final String customerId, final String paymentMethodId,
|
||||
@Nullable final String currentSubscriptionId) throws SubscriptionInvalidArgumentsException {
|
||||
final CustomerUpdateParams params = CustomerUpdateParams.builder()
|
||||
.setInvoiceSettings(InvoiceSettings.builder()
|
||||
.setDefaultPaymentMethod(paymentMethodId)
|
||||
.build())
|
||||
.build();
|
||||
try {
|
||||
stripeClient.v1().customers().update(customerId, params, commonOptions());
|
||||
} catch (final InvalidRequestException e) {
|
||||
// Could happen if the paymentMethodId was bunk or the client didn't actually finish setting it up
|
||||
throw new SubscriptionInvalidArgumentsException(e.getMessage());
|
||||
} catch (final StripeException e) {
|
||||
throw new UncheckedIOException(new IOException(e));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String createPaymentMethodSetupToken(String customerId) {
|
||||
SetupIntentCreateParams params = SetupIntentCreateParams.builder()
|
||||
public String createPaymentMethodSetupToken(final String customerId) {
|
||||
final SetupIntentCreateParams params = SetupIntentCreateParams.builder()
|
||||
.setCustomer(customerId)
|
||||
.build();
|
||||
try {
|
||||
return stripeClient.v1().setupIntents().create(params, commonOptions()).getClientSecret();
|
||||
} catch (StripeException e) {
|
||||
} catch (final StripeException e) {
|
||||
throw new UncheckedIOException(new IOException(e));
|
||||
}
|
||||
}
|
||||
@@ -207,70 +206,65 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a payment intent. May throw a {@link SubscriptionInvalidAmountException} if stripe rejects the
|
||||
* attempt if the amount is too large or too small
|
||||
* Creates a payment intent. May throw a {@link SubscriptionInvalidAmountException} if stripe rejects the attempt if
|
||||
* the amount is too large or too small
|
||||
*/
|
||||
public CompletableFuture<PaymentIntent> createPaymentIntent(final String currency,
|
||||
public PaymentIntent createPaymentIntent(final String currency,
|
||||
final long amount,
|
||||
final long level,
|
||||
@Nullable final ClientPlatform clientPlatform) {
|
||||
@Nullable final ClientPlatform clientPlatform) throws SubscriptionInvalidAmountException {
|
||||
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
final PaymentIntentCreateParams.Builder builder = PaymentIntentCreateParams.builder()
|
||||
.setAmount(amount)
|
||||
.setCurrency(currency.toLowerCase(Locale.ROOT))
|
||||
.setDescription(boostDescription)
|
||||
.setCaptureMethod(PaymentIntentCreateParams.CaptureMethod.AUTOMATIC)
|
||||
.putMetadata("level", Long.toString(level));
|
||||
final PaymentIntentCreateParams.Builder builder = PaymentIntentCreateParams.builder()
|
||||
.setAmount(amount)
|
||||
.setCurrency(currency.toLowerCase(Locale.ROOT))
|
||||
.setDescription(boostDescription)
|
||||
.setCaptureMethod(PaymentIntentCreateParams.CaptureMethod.AUTOMATIC)
|
||||
.putMetadata("level", Long.toString(level));
|
||||
|
||||
if (clientPlatform != null) {
|
||||
builder.putMetadata(METADATA_KEY_CLIENT_PLATFORM, clientPlatform.name().toLowerCase());
|
||||
if (clientPlatform != null) {
|
||||
builder.putMetadata(METADATA_KEY_CLIENT_PLATFORM, clientPlatform.name().toLowerCase());
|
||||
}
|
||||
|
||||
try {
|
||||
return stripeClient.v1().paymentIntents().create(builder.build(), commonOptions());
|
||||
} catch (final StripeException e) {
|
||||
final String errorCode = e.getCode() == null
|
||||
? "unknown"
|
||||
: e.getCode().toLowerCase(Locale.ROOT);
|
||||
switch (errorCode) {
|
||||
case "amount_too_small", "amount_too_large" -> throw new SubscriptionInvalidAmountException(errorCode);
|
||||
default -> throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
try {
|
||||
return stripeClient.v1().paymentIntents().create(builder.build(), commonOptions());
|
||||
} catch (StripeException e) {
|
||||
final String errorCode = e.getCode() == null
|
||||
? "unknown"
|
||||
: e.getCode().toLowerCase(Locale.ROOT);
|
||||
switch (errorCode) {
|
||||
case "amount_too_small","amount_too_large" ->
|
||||
throw ExceptionUtils.wrap(new SubscriptionInvalidAmountException(errorCode));
|
||||
default -> throw new CompletionException(e);
|
||||
}
|
||||
}
|
||||
}, executor);
|
||||
}
|
||||
}
|
||||
|
||||
public CompletableFuture<Optional<PaymentDetails>> getPaymentDetails(final String paymentIntentId) {
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
try {
|
||||
final PaymentIntent paymentIntent = getPaymentIntent(paymentIntentId);
|
||||
public Optional<PaymentDetails> getPaymentDetails(final String paymentIntentId) throws IOException {
|
||||
try {
|
||||
final PaymentIntent paymentIntent = getPaymentIntent(paymentIntentId);
|
||||
|
||||
ChargeFailure chargeFailure = null;
|
||||
if (paymentIntent.getLatestChargeObject() != null) {
|
||||
final Charge charge = paymentIntent.getLatestChargeObject();
|
||||
if (charge.getFailureCode() != null || charge.getFailureMessage() != null) {
|
||||
chargeFailure = createChargeFailure(charge);
|
||||
}
|
||||
}
|
||||
|
||||
return Optional.of(new PaymentDetails(paymentIntent.getId(),
|
||||
paymentIntent.getMetadata() == null ? Collections.emptyMap() : paymentIntent.getMetadata(),
|
||||
getPaymentStatusForStatus(paymentIntent.getStatus()),
|
||||
Instant.ofEpochSecond(paymentIntent.getCreated()),
|
||||
chargeFailure));
|
||||
} catch (StripeException e) {
|
||||
if (e.getStatusCode() == 404) {
|
||||
return Optional.empty();
|
||||
} else {
|
||||
throw new CompletionException(e);
|
||||
ChargeFailure chargeFailure = null;
|
||||
if (paymentIntent.getLatestChargeObject() != null) {
|
||||
final Charge charge = paymentIntent.getLatestChargeObject();
|
||||
if (charge.getFailureCode() != null || charge.getFailureMessage() != null) {
|
||||
chargeFailure = createChargeFailure(charge);
|
||||
}
|
||||
}
|
||||
}, executor);
|
||||
|
||||
return Optional.of(new PaymentDetails(paymentIntent.getId(),
|
||||
paymentIntent.getMetadata() == null ? Collections.emptyMap() : paymentIntent.getMetadata(),
|
||||
getPaymentStatusForStatus(paymentIntent.getStatus()),
|
||||
Instant.ofEpochSecond(paymentIntent.getCreated()),
|
||||
chargeFailure));
|
||||
} catch (final StripeException e) {
|
||||
if (e.getStatusCode() == 404) {
|
||||
return Optional.empty();
|
||||
} else {
|
||||
throw new IOException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static PaymentStatus getPaymentStatusForStatus(String status) {
|
||||
private static PaymentStatus getPaymentStatusForStatus(final String status) {
|
||||
return switch (status.toLowerCase(Locale.ROOT)) {
|
||||
case "processing" -> PaymentStatus.PROCESSING;
|
||||
case "succeeded" -> PaymentStatus.SUCCEEDED;
|
||||
@@ -283,13 +277,13 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
}
|
||||
|
||||
@Override
|
||||
public SubscriptionId createSubscription(String customerId, String priceId, long level,
|
||||
long lastSubscriptionCreatedAt)
|
||||
public SubscriptionId createSubscription(final String customerId, final String priceId, final long level,
|
||||
final long lastSubscriptionCreatedAt)
|
||||
throws SubscriptionProcessorException, SubscriptionInvalidIdempotencyKeyException,
|
||||
SubscriptionPaymentRequiresActionException {
|
||||
// this relies on Stripe's idempotency key to avoid creating more than one subscription if the client
|
||||
// retries this request
|
||||
SubscriptionCreateParams params = SubscriptionCreateParams.builder()
|
||||
final SubscriptionCreateParams params = SubscriptionCreateParams.builder()
|
||||
.setCustomer(customerId)
|
||||
.setOffSession(true)
|
||||
.setPaymentBehavior(SubscriptionCreateParams.PaymentBehavior.ERROR_IF_INCOMPLETE)
|
||||
@@ -307,11 +301,11 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
params,
|
||||
commonOptions(generateIdempotencyKeyForCreateSubscription(customerId, lastSubscriptionCreatedAt)));
|
||||
return new SubscriptionId(subscription.getId());
|
||||
} catch (IdempotencyException e) {
|
||||
} catch (final IdempotencyException e) {
|
||||
throw new SubscriptionInvalidIdempotencyKeyException(e.getStripeError().getMessage());
|
||||
} catch (CardException e) {
|
||||
} catch (final CardException e) {
|
||||
throw new SubscriptionProcessorException(getProvider(), createChargeFailureFromCardException(e));
|
||||
} catch (StripeException e) {
|
||||
} catch (final StripeException e) {
|
||||
if ("subscription_payment_intent_requires_action".equals(e.getCode())) {
|
||||
throw new SubscriptionPaymentRequiresActionException();
|
||||
}
|
||||
@@ -320,7 +314,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
}
|
||||
|
||||
@Override
|
||||
public SubscriptionId updateSubscription(Object subscriptionObj, String priceId, long level, String idempotencyKey)
|
||||
public SubscriptionId updateSubscription(final Object subscriptionObj, final String priceId, final long level, final String idempotencyKey)
|
||||
throws SubscriptionInvalidIdempotencyKeyException, SubscriptionPaymentRequiresActionException,
|
||||
SubscriptionProcessorException {
|
||||
|
||||
@@ -332,7 +326,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
return createSubscription(subscription.getCustomer(), priceId, level, subscription.getCreated());
|
||||
}
|
||||
|
||||
List<SubscriptionUpdateParams.Item> items = new ArrayList<>();
|
||||
final List<SubscriptionUpdateParams.Item> items = new ArrayList<>();
|
||||
try {
|
||||
final StripeCollection<SubscriptionItem> subscriptionItems = stripeClient.v1().subscriptionItems()
|
||||
.list(SubscriptionItemListParams.builder().setSubscription(subscription.getId()).build(),
|
||||
@@ -346,7 +340,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
items.add(SubscriptionUpdateParams.Item.builder()
|
||||
.setPrice(priceId)
|
||||
.build());
|
||||
SubscriptionUpdateParams params = SubscriptionUpdateParams.builder()
|
||||
final SubscriptionUpdateParams params = SubscriptionUpdateParams.builder()
|
||||
.putMetadata(METADATA_KEY_LEVEL, Long.toString(level))
|
||||
|
||||
// since badge redemption is untrackable by design and unrevokable, subscription changes must be immediate and
|
||||
@@ -360,56 +354,57 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
final Subscription subscription1 = stripeClient.v1().subscriptions().update(subscription.getId(), params,
|
||||
commonOptions(generateIdempotencyKeyForSubscriptionUpdate(subscription.getCustomer(), idempotencyKey)));
|
||||
return new SubscriptionId(subscription1.getId());
|
||||
} catch (IdempotencyException e) {
|
||||
} catch (final IdempotencyException e) {
|
||||
throw new SubscriptionInvalidIdempotencyKeyException(e.getStripeError().getMessage());
|
||||
} catch (CardException e) {
|
||||
} catch (final CardException e) {
|
||||
throw new SubscriptionProcessorException(getProvider(), createChargeFailureFromCardException(e));
|
||||
} catch (StripeException e) {
|
||||
} catch (final StripeException e) {
|
||||
throw new UncheckedIOException(new IOException(e));
|
||||
}
|
||||
}
|
||||
|
||||
/// Retrieves the subscription object with `latest_invoice.payments` expanded
|
||||
@Override
|
||||
public Object getSubscription(String subscriptionId) {
|
||||
SubscriptionRetrieveParams params = SubscriptionRetrieveParams.builder()
|
||||
public Object getSubscription(final String subscriptionId) {
|
||||
final SubscriptionRetrieveParams params = SubscriptionRetrieveParams.builder()
|
||||
.addExpand("latest_invoice.payments")
|
||||
.build();
|
||||
try {
|
||||
return stripeClient.v1().subscriptions().retrieve(subscriptionId, params, commonOptions());
|
||||
} catch (StripeException e) {
|
||||
} catch (final StripeException e) {
|
||||
throw new UncheckedIOException(new IOException(e));
|
||||
}
|
||||
}
|
||||
|
||||
/// Retrieves the payment intent object with `latest_charge` expanded
|
||||
public PaymentIntent getPaymentIntent(String paymentIntentId) throws StripeException {
|
||||
PaymentIntentRetrieveParams params = PaymentIntentRetrieveParams.builder()
|
||||
public PaymentIntent getPaymentIntent(final String paymentIntentId) throws StripeException {
|
||||
final PaymentIntentRetrieveParams params = PaymentIntentRetrieveParams.builder()
|
||||
.addExpand("latest_charge")
|
||||
.build();
|
||||
return stripeClient.v1().paymentIntents().retrieve(paymentIntentId, params, commonOptions());
|
||||
}
|
||||
|
||||
public Charge getCharge(String chargeId) {
|
||||
ChargeRetrieveParams params = ChargeRetrieveParams.builder()
|
||||
public Charge getCharge(final String chargeId) {
|
||||
final ChargeRetrieveParams params = ChargeRetrieveParams.builder()
|
||||
.build();
|
||||
try {
|
||||
return stripeClient.v1().charges().retrieve(chargeId, params, commonOptions());
|
||||
} catch (StripeException e) {
|
||||
} catch (final StripeException e) {
|
||||
throw new UncheckedIOException(new IOException(e));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void cancelAllActiveSubscriptions(String customerId) {
|
||||
public void cancelAllActiveSubscriptions(final String customerId) {
|
||||
final Customer customer = getCustomer(customerId);
|
||||
if (customer == null) {
|
||||
throw new UncheckedIOException(new IOException("no customer record found for id " + customerId));
|
||||
}
|
||||
if (StringUtils.isBlank(customer.getId()) || (!customer.getId().equals(customerId))) {
|
||||
logger.error("customer ID returned by Stripe ({}) did not match query ({})", customerId, customer.getSubscriptions());
|
||||
throw new UncheckedIOException(new IOException("unexpected customer ID returned by Stripe"));
|
||||
}
|
||||
if (customer == null) {
|
||||
throw new UncheckedIOException(new IOException("no customer record found for id " + customerId));
|
||||
}
|
||||
if (StringUtils.isBlank(customer.getId()) || (!customer.getId().equals(customerId))) {
|
||||
logger.error("customer ID returned by Stripe ({}) did not match query ({})", customerId,
|
||||
customer.getSubscriptions());
|
||||
throw new UncheckedIOException(new IOException("unexpected customer ID returned by Stripe"));
|
||||
}
|
||||
|
||||
final Collection<Subscription> subscriptions = listNonCanceledSubscriptions(customer);
|
||||
if (subscriptions.stream()
|
||||
@@ -423,20 +418,20 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
.toList());
|
||||
}
|
||||
|
||||
public Collection<Subscription> listNonCanceledSubscriptions(Customer customer) {
|
||||
SubscriptionListParams params = SubscriptionListParams.builder()
|
||||
public Collection<Subscription> listNonCanceledSubscriptions(final Customer customer) {
|
||||
final SubscriptionListParams params = SubscriptionListParams.builder()
|
||||
.setCustomer(customer.getId())
|
||||
.build();
|
||||
try {
|
||||
return Lists.newArrayList(
|
||||
stripeClient.v1().subscriptions().list(params, commonOptions()).autoPagingIterable());
|
||||
} catch (StripeException e) {
|
||||
} catch (final StripeException e) {
|
||||
throw new UncheckedIOException(new IOException(e));
|
||||
}
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
void endSubscription(Subscription subscription) {
|
||||
void endSubscription(final Subscription subscription) {
|
||||
|
||||
final SubscriptionStatus status = SubscriptionStatus.forApiValue(subscription.getStatus());
|
||||
switch (status) {
|
||||
@@ -459,30 +454,30 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
cancelSubscriptionAtEndOfCurrentPeriod(subscription);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
private void cancelSubscriptionImmediately(Subscription subscription) {
|
||||
SubscriptionCancelParams params = SubscriptionCancelParams.builder().build();
|
||||
private void cancelSubscriptionImmediately(final Subscription subscription) {
|
||||
final SubscriptionCancelParams params = SubscriptionCancelParams.builder().build();
|
||||
try {
|
||||
stripeClient.v1().subscriptions().cancel(subscription.getId(), params, commonOptions());
|
||||
} catch (StripeException e) {
|
||||
} catch (final StripeException e) {
|
||||
throw new UncheckedIOException(new IOException(e));
|
||||
}
|
||||
}
|
||||
|
||||
private void cancelSubscriptionAtEndOfCurrentPeriod(Subscription subscription) {
|
||||
SubscriptionUpdateParams params = SubscriptionUpdateParams.builder()
|
||||
private void cancelSubscriptionAtEndOfCurrentPeriod(final Subscription subscription) {
|
||||
final SubscriptionUpdateParams params = SubscriptionUpdateParams.builder()
|
||||
.setCancelAtPeriodEnd(true)
|
||||
.build();
|
||||
try {
|
||||
stripeClient.v1().subscriptions().update(subscription.getId(), params, commonOptions());
|
||||
} catch (StripeException e) {
|
||||
} catch (final StripeException e) {
|
||||
throw new UncheckedIOException(new IOException(e));
|
||||
}
|
||||
}
|
||||
|
||||
public Collection<SubscriptionItem> getItemsForSubscription(Subscription subscription) {
|
||||
public Collection<SubscriptionItem> getItemsForSubscription(final Subscription subscription) {
|
||||
try {
|
||||
final StripeCollection<SubscriptionItem> subscriptionItems = stripeClient.v1().subscriptionItems().list(
|
||||
SubscriptionItemListParams.builder().setSubscription(subscription.getId()).build(), commonOptions());
|
||||
@@ -493,7 +488,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
}
|
||||
}
|
||||
|
||||
public Price getPriceForSubscription(Subscription subscription) {
|
||||
public Price getPriceForSubscription(final Subscription subscription) {
|
||||
final Collection<SubscriptionItem> subscriptionItems = getItemsForSubscription(subscription);
|
||||
if (subscriptionItems.isEmpty()) {
|
||||
throw new IllegalStateException("no items found in subscription " + subscription.getId());
|
||||
@@ -505,12 +500,12 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
}
|
||||
}
|
||||
|
||||
private Product getProductForSubscription(Subscription subscription) {
|
||||
private Product getProductForSubscription(final Subscription subscription) {
|
||||
return getProductForPrice(getPriceForSubscription(subscription).getId());
|
||||
}
|
||||
|
||||
@Override
|
||||
public LevelAndCurrency getLevelAndCurrencyForSubscription(Object subscriptionObj) {
|
||||
public LevelAndCurrency getLevelAndCurrencyForSubscription(final Object subscriptionObj) {
|
||||
final Subscription subscription = getSubscription(subscriptionObj);
|
||||
|
||||
final Product product = getProductForSubscription(subscription);
|
||||
@@ -519,25 +514,25 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
subscription.getCurrency().toLowerCase(Locale.ROOT));
|
||||
}
|
||||
|
||||
public long getLevelForPrice(Price price) {
|
||||
public long getLevelForPrice(final Price price) {
|
||||
return getLevelForProduct(getProductForPrice(price.getId()));
|
||||
}
|
||||
|
||||
public Product getProductForPrice(String priceId) {
|
||||
PriceRetrieveParams params = PriceRetrieveParams.builder().addExpand("product").build();
|
||||
public Product getProductForPrice(final String priceId) {
|
||||
final PriceRetrieveParams params = PriceRetrieveParams.builder().addExpand("product").build();
|
||||
try {
|
||||
return stripeClient.v1().prices().retrieve(priceId, params, commonOptions()).getProductObject();
|
||||
} catch (StripeException e) {
|
||||
} catch (final StripeException e) {
|
||||
throw new UncheckedIOException(new IOException(e));
|
||||
}
|
||||
}
|
||||
|
||||
public long getLevelForProduct(Product product) {
|
||||
public long getLevelForProduct(final Product product) {
|
||||
return Long.parseLong(product.getMetadata().get(METADATA_KEY_LEVEL));
|
||||
}
|
||||
|
||||
private static ChargeFailure createChargeFailure(final Charge charge) {
|
||||
Charge.Outcome outcome = charge.getOutcome();
|
||||
final Charge.Outcome outcome = charge.getOutcome();
|
||||
return new ChargeFailure(
|
||||
charge.getFailureCode(),
|
||||
charge.getFailureMessage(),
|
||||
@@ -546,7 +541,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
outcome != null ? outcome.getType() : null);
|
||||
}
|
||||
|
||||
private static ChargeFailure createChargeFailureFromCardException(CardException e) {
|
||||
private static ChargeFailure createChargeFailureFromCardException(final CardException e) {
|
||||
return new ChargeFailure(
|
||||
StringUtils.defaultIfBlank(e.getDeclineCode(), e.getCode()),
|
||||
e.getStripeError().getMessage(),
|
||||
@@ -583,7 +578,8 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
|
||||
if (charge.getPaymentMethodDetails() != null
|
||||
&& charge.getPaymentMethodDetails().getType() != null) {
|
||||
paymentMethod = getPaymentMethodFromStripeString(charge.getPaymentMethodDetails().getType(), invoice.getId());
|
||||
paymentMethod = getPaymentMethodFromStripeString(charge.getPaymentMethodDetails().getType(),
|
||||
invoice.getId());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -604,7 +600,8 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
);
|
||||
}
|
||||
|
||||
private static PaymentMethod getPaymentMethodFromStripeString(final String paymentMethodString, final String invoiceId) {
|
||||
private static PaymentMethod getPaymentMethodFromStripeString(final String paymentMethodString,
|
||||
final String invoiceId) {
|
||||
return switch (paymentMethodString) {
|
||||
case "sepa_debit" -> PaymentMethod.SEPA_DEBIT;
|
||||
case "card" -> PaymentMethod.CARD;
|
||||
@@ -615,7 +612,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
};
|
||||
}
|
||||
|
||||
private Subscription getSubscription(Object subscriptionObj) {
|
||||
private Subscription getSubscription(final Object subscriptionObj) {
|
||||
if (!(subscriptionObj instanceof final Subscription subscription)) {
|
||||
throw new IllegalArgumentException("invalid subscription object: " + subscriptionObj.getClass().getName());
|
||||
}
|
||||
@@ -624,18 +621,19 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
}
|
||||
|
||||
@Override
|
||||
public ReceiptItem getReceiptItem(String subscriptionId)
|
||||
public ReceiptItem getReceiptItem(final String subscriptionId)
|
||||
throws SubscriptionPaymentRequiredException, SubscriptionReceiptRequestedForOpenPaymentException {
|
||||
final Invoice invoice = getSubscription(getSubscription(subscriptionId)).getLatestInvoiceObject();
|
||||
return convertInvoiceToReceipt(invoice, subscriptionId);
|
||||
}
|
||||
|
||||
private ReceiptItem convertInvoiceToReceipt(Invoice latestSubscriptionInvoice, String subscriptionId)
|
||||
private ReceiptItem convertInvoiceToReceipt(final Invoice latestSubscriptionInvoice, final String subscriptionId)
|
||||
throws SubscriptionReceiptRequestedForOpenPaymentException, SubscriptionPaymentRequiredException {
|
||||
if (latestSubscriptionInvoice == null) {
|
||||
throw new SubscriptionReceiptRequestedForOpenPaymentException();
|
||||
}
|
||||
if ("open".equalsIgnoreCase(latestSubscriptionInvoice.getStatus()) || "draft".equalsIgnoreCase(latestSubscriptionInvoice.getStatus())) {
|
||||
if ("open".equalsIgnoreCase(latestSubscriptionInvoice.getStatus()) || "draft".equalsIgnoreCase(
|
||||
latestSubscriptionInvoice.getStatus())) {
|
||||
throw new SubscriptionReceiptRequestedForOpenPaymentException();
|
||||
}
|
||||
if (!"paid".equalsIgnoreCase(latestSubscriptionInvoice.getStatus())) {
|
||||
@@ -660,7 +658,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
}
|
||||
|
||||
final Collection<InvoiceLineItem> invoiceLineItems = getInvoiceLineItemsForInvoice(latestSubscriptionInvoice);
|
||||
Collection<InvoiceLineItem> subscriptionLineItems = invoiceLineItems.stream()
|
||||
final Collection<InvoiceLineItem> subscriptionLineItems = invoiceLineItems.stream()
|
||||
.filter(invoiceLineItem -> "subscription_item_details".equalsIgnoreCase(invoiceLineItem.getParent().getType()))
|
||||
.toList();
|
||||
if (subscriptionLineItems.isEmpty()) {
|
||||
@@ -673,11 +671,11 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
+ "; invoiceId=" + latestSubscriptionInvoice.getId() + "; count=" + subscriptionLineItems.size());
|
||||
}
|
||||
|
||||
InvoiceLineItem subscriptionLineItem = subscriptionLineItems.stream().findAny().get();
|
||||
final InvoiceLineItem subscriptionLineItem = subscriptionLineItems.stream().findAny().get();
|
||||
return getReceiptForSubscription(subscriptionLineItem, latestSubscriptionInvoice);
|
||||
}
|
||||
|
||||
private ReceiptItem getReceiptForSubscription(InvoiceLineItem subscriptionLineItem, Invoice invoice) {
|
||||
private ReceiptItem getReceiptForSubscription(final InvoiceLineItem subscriptionLineItem, final Invoice invoice) {
|
||||
final Instant paidAt;
|
||||
if (invoice.getStatusTransitions().getPaidAt() != null) {
|
||||
paidAt = Instant.ofEpochSecond(invoice.getStatusTransitions().getPaidAt());
|
||||
@@ -693,7 +691,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
getLevelForProduct(product));
|
||||
}
|
||||
|
||||
public Collection<InvoiceLineItem> getInvoiceLineItemsForInvoice(Invoice invoice) {
|
||||
public Collection<InvoiceLineItem> getInvoiceLineItemsForInvoice(final Invoice invoice) {
|
||||
try {
|
||||
final StripeCollection<InvoiceLineItem> lineItems = stripeClient.v1().invoices().lineItems()
|
||||
.list(invoice.getId(), commonOptions());
|
||||
@@ -703,31 +701,31 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
}
|
||||
}
|
||||
|
||||
public CompletableFuture<String> getGeneratedSepaIdFromSetupIntent(String setupIntentId) {
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
SetupIntentRetrieveParams params = SetupIntentRetrieveParams.builder()
|
||||
.addExpand("latest_attempt")
|
||||
.build();
|
||||
try {
|
||||
final SetupIntent setupIntent = stripeClient.v1().setupIntents().retrieve(setupIntentId, params, commonOptions());
|
||||
if (setupIntent.getLatestAttemptObject() == null
|
||||
|| setupIntent.getLatestAttemptObject().getPaymentMethodDetails() == null
|
||||
|| setupIntent.getLatestAttemptObject().getPaymentMethodDetails().getIdeal() == null
|
||||
|| setupIntent.getLatestAttemptObject().getPaymentMethodDetails().getIdeal().getGeneratedSepaDebit() == null) {
|
||||
// This usually indicates that the client has made requests out of order, either by not confirming
|
||||
// the SetupIntent or not having the user authorize the transaction.
|
||||
logger.debug("setupIntent {} missing expected fields", setupIntentId);
|
||||
throw ExceptionUtils.wrap(new SubscriptionProcessorConflictException());
|
||||
}
|
||||
return setupIntent.getLatestAttemptObject().getPaymentMethodDetails().getIdeal().getGeneratedSepaDebit();
|
||||
} catch (StripeException e) {
|
||||
if (e.getStatusCode() == 404) {
|
||||
throw ExceptionUtils.wrap(new SubscriptionNotFoundException());
|
||||
}
|
||||
logger.error("unexpected error from Stripe when retrieving setupIntent {}", setupIntentId, e);
|
||||
throw ExceptionUtils.wrap(e);
|
||||
public String getGeneratedSepaIdFromSetupIntent(final String setupIntentId)
|
||||
throws SubscriptionNotFoundException, SubscriptionProcessorConflictException, IOException {
|
||||
final SetupIntentRetrieveParams params = SetupIntentRetrieveParams.builder()
|
||||
.addExpand("latest_attempt")
|
||||
.build();
|
||||
try {
|
||||
final SetupIntent setupIntent = stripeClient.v1().setupIntents().retrieve(setupIntentId, params, commonOptions());
|
||||
if (setupIntent.getLatestAttemptObject() == null
|
||||
|| setupIntent.getLatestAttemptObject().getPaymentMethodDetails() == null
|
||||
|| setupIntent.getLatestAttemptObject().getPaymentMethodDetails().getIdeal() == null
|
||||
|| setupIntent.getLatestAttemptObject().getPaymentMethodDetails().getIdeal().getGeneratedSepaDebit()
|
||||
== null) {
|
||||
// This usually indicates that the client has made requests out of order, either by not confirming
|
||||
// the SetupIntent or not having the user authorize the transaction.
|
||||
logger.debug("setupIntent {} missing expected fields", setupIntentId);
|
||||
throw new SubscriptionProcessorConflictException();
|
||||
}
|
||||
}, executor);
|
||||
return setupIntent.getLatestAttemptObject().getPaymentMethodDetails().getIdeal().getGeneratedSepaDebit();
|
||||
} catch (final StripeException e) {
|
||||
if (e.getStatusCode() == 404) {
|
||||
throw new SubscriptionNotFoundException();
|
||||
}
|
||||
logger.error("unexpected error from Stripe when retrieving setupIntent {}", setupIntentId, e);
|
||||
throw new IOException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private Optional<InvoicePayment> getMostRecentInvoicePayment(final Invoice invoice) {
|
||||
@@ -757,32 +755,32 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
* it is intentionally sending a repeat of the update to level 2 request because user is changing again, so in this
|
||||
* case we derive idempotency from the client.
|
||||
*/
|
||||
private String generateIdempotencyKeyForSubscriptionUpdate(String customerId, String idempotencyKey) {
|
||||
private String generateIdempotencyKeyForSubscriptionUpdate(final String customerId, final String idempotencyKey) {
|
||||
return generateIdempotencyKey("subscriptionUpdate", mac -> {
|
||||
mac.update(customerId.getBytes(StandardCharsets.UTF_8));
|
||||
mac.update(idempotencyKey.getBytes(StandardCharsets.UTF_8));
|
||||
});
|
||||
}
|
||||
|
||||
private String generateIdempotencyKeyForSubscriberUser(byte[] subscriberUser) {
|
||||
private String generateIdempotencyKeyForSubscriberUser(final byte[] subscriberUser) {
|
||||
return generateIdempotencyKey("subscriberUser", mac -> mac.update(subscriberUser));
|
||||
}
|
||||
|
||||
private String generateIdempotencyKeyForCreateSubscription(String customerId, long lastSubscriptionCreatedAt) {
|
||||
private String generateIdempotencyKeyForCreateSubscription(final String customerId, final long lastSubscriptionCreatedAt) {
|
||||
return generateIdempotencyKey("customerId", mac -> {
|
||||
mac.update(customerId.getBytes(StandardCharsets.UTF_8));
|
||||
mac.update(Conversions.longToByteArray(lastSubscriptionCreatedAt));
|
||||
});
|
||||
}
|
||||
|
||||
private String generateIdempotencyKey(String type, Consumer<Mac> byteConsumer) {
|
||||
private String generateIdempotencyKey(final String type, final Consumer<Mac> byteConsumer) {
|
||||
try {
|
||||
Mac mac = Mac.getInstance("HmacSHA256");
|
||||
final Mac mac = Mac.getInstance("HmacSHA256");
|
||||
mac.init(new SecretKeySpec(idempotencyKeyGenerator, "HmacSHA256"));
|
||||
mac.update(type.getBytes(StandardCharsets.UTF_8));
|
||||
byteConsumer.accept(mac);
|
||||
return Base64.getUrlEncoder().encodeToString(mac.doFinal());
|
||||
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
|
||||
} catch (final NoSuchAlgorithmException | InvalidKeyException e) {
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.util;
|
||||
|
||||
/// Represents an operation that two argument and returns a result, but may throw a checked exception. Unlike most other
|
||||
/// functional interfaces, `ThrowingBiFunction` is expected to operate via side-effects.
|
||||
@FunctionalInterface
|
||||
public interface ThrowingBiFunction<T, U, R, E extends Exception> {
|
||||
|
||||
/// Performs this operation on the given arguments and returns a result.
|
||||
///
|
||||
/// @param t the first input argument
|
||||
/// @param u the second input argument
|
||||
/// @return the result of applying the function
|
||||
/// @throws E at the implementation's discretion
|
||||
R apply(T t, U u) throws E;
|
||||
}
|
||||
+3
-3
@@ -351,7 +351,7 @@ public record CommandDependencies(
|
||||
final GenericServerSecretParams backupsGenericZkSecretParams;
|
||||
try {
|
||||
backupsGenericZkSecretParams =
|
||||
new GenericServerSecretParams(configuration.getBackupsZkConfig().serverSecret().value());
|
||||
new GenericServerSecretParams(configuration.getChatZkConfig().serverSecret().value());
|
||||
} catch (InvalidInputException e) {
|
||||
throw new IllegalArgumentException(e);
|
||||
}
|
||||
@@ -368,7 +368,7 @@ public record CommandDependencies(
|
||||
secureValueRecoveryBCredentialsGenerator,
|
||||
secureValueRecoveryBClient,
|
||||
clock,
|
||||
dynamicConfigurationManager);
|
||||
configuration.getBackupConfiguration());
|
||||
|
||||
final IssuedReceiptsManager issuedReceiptsManager = new IssuedReceiptsManager(
|
||||
configuration.getDynamoDbTables().getIssuedReceipts().getTableName(),
|
||||
@@ -377,7 +377,7 @@ public record CommandDependencies(
|
||||
configuration.getDynamoDbTables().getIssuedReceipts().getGenerator(),
|
||||
configuration.getDynamoDbTables().getIssuedReceipts().getmaxIssuedReceiptsPerPaymentId());
|
||||
|
||||
final ServerSecretParams zkSecretParams = new ServerSecretParams(configuration.getZkConfig().serverSecret().value());
|
||||
final ServerSecretParams zkSecretParams = new ServerSecretParams(configuration.getGroupsZkConfig().serverSecret().value());
|
||||
final ServerZkReceiptOperations zkReceiptOperations = new ServerZkReceiptOperations(zkSecretParams);
|
||||
GooglePlayBillingManager googlePlayBillingManager = new GooglePlayBillingManager(
|
||||
new ByteArrayInputStream(configuration.getGooglePlayBilling().credentialsJson().getBytes(StandardCharsets.UTF_8)),
|
||||
|
||||
@@ -30,11 +30,15 @@ message AccountIdentifiers {
|
||||
repeated ServiceIdentifier service_identifiers = 1;
|
||||
|
||||
// The phone number associated with the identified account.
|
||||
string e164 = 2;
|
||||
string e164 = 2 [(org.signal.chat.require.e164) = true];
|
||||
|
||||
// The username hash (if any) associated with the identified account. May be
|
||||
// empty if no username is associated with the identified account.
|
||||
bytes username_hash = 3;
|
||||
bytes username_hash = 3 [(org.signal.chat.require.exactlySize) = 0, (org.signal.chat.require.exactlySize) = 32];
|
||||
|
||||
// The username link handle UUID associated with the identified account.
|
||||
// May be empty if no username is associated with the identified account.
|
||||
bytes username_link_handle = 4 [(org.signal.chat.require.exactlySize) = 0, (org.signal.chat.require.exactlySize) = 16];
|
||||
}
|
||||
|
||||
message EcPreKey {
|
||||
|
||||
@@ -7,7 +7,7 @@ syntax = "proto3";
|
||||
|
||||
option java_multiple_files = true;
|
||||
|
||||
package org.signal.chat.one_time_donations;
|
||||
package org.signal.chat.purchase;
|
||||
|
||||
import "org/signal/chat/require.proto";
|
||||
import "org/signal/chat/errors.proto";
|
||||
@@ -16,9 +16,7 @@ import "org/signal/chat/subscriptions.proto";
|
||||
|
||||
// Service for making one-time donation payments (boost and gift)
|
||||
//
|
||||
// Note that these are siblings of the RPCs in the Subscriptions service. One-time payments do
|
||||
// not require the subscription management methods in that service, though the configuration at
|
||||
// Subscriptions.GetConfiguration is shared between subscription and one-time payments.
|
||||
// Configuration for one-time donations can be found in ProductConfiguration.
|
||||
service OneTimeDonations {
|
||||
option (require.auth) = AUTH_ONLY_ANONYMOUS;
|
||||
|
||||
@@ -59,7 +57,7 @@ message CreateBoostRequest {
|
||||
// The level for the boost payment
|
||||
uint64 level = 3 [(require.range).min = 1];
|
||||
// The payment method
|
||||
subscriptions.PaymentMethod payment_method = 4 [(require.specified) = true];
|
||||
PaymentMethod payment_method = 4 [(require.specified) = true];
|
||||
// A donation permit retrieved from Donations.createDonationPermit
|
||||
bytes donation_permit = 5 [(require.nonEmpty) = true];
|
||||
}
|
||||
@@ -78,6 +76,8 @@ message CreateBoostResponse {
|
||||
errors.FailedPrecondition unsupported_level = 5 [(tag.reason) = "unsupported_level"];
|
||||
// Donation permit was invalid or already spent
|
||||
errors.FailedZkAuthentication permit_rejected = 6 [(tag.reason) = "permit_rejected"];
|
||||
// The amount in the specified currency is not supported by the payment provider
|
||||
errors.FailedPrecondition invalid_amount = 7 [(tag.reason) = "invalid_amount"];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -137,6 +137,8 @@ message ConfirmPayPalBoostResponse {
|
||||
errors.FailedPrecondition unsupported_currency = 3 [(tag.reason) = "unsupported_currency"];
|
||||
// The requested level is not a valid one-time donation level
|
||||
errors.FailedPrecondition unsupported_level = 4 [(tag.reason) = "unsupported_level"];
|
||||
// The payment failed; see charge failure details
|
||||
ChargeFailure charge_failure = 5 [(tag.reason) = "charge_failure"];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -146,7 +148,7 @@ message CreateBoostReceiptCredentialsRequest {
|
||||
// ZK blind-signature receipt credential request bytes
|
||||
bytes receipt_credential_request = 2 [(require.nonEmpty) = true];
|
||||
// The processor that handled the payment
|
||||
subscriptions.PaymentProvider processor = 3 [(require.specified) = true];
|
||||
PaymentProvider processor = 3 [(require.specified) = true];
|
||||
}
|
||||
|
||||
message CreateBoostReceiptCredentialsResponse {
|
||||
@@ -158,7 +160,7 @@ message CreateBoostReceiptCredentialsResponse {
|
||||
// Payment is still processing; client should retry
|
||||
errors.FailedPrecondition payment_still_processing = 2 [(tag.reason) = "payment_still_processing"];
|
||||
// Payment failed
|
||||
subscriptions.PaymentRequired payment_required = 3 [(tag.reason) = "payment_required"];
|
||||
PaymentRequired payment_required = 3 [(tag.reason) = "payment_required"];
|
||||
// Payment intent not found
|
||||
errors.NotFound payment_not_found = 4 [(tag.reason) = "payment_not_found"];
|
||||
// A receipt credential was already issued for this payment
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
syntax = "proto3";
|
||||
|
||||
option java_multiple_files = true;
|
||||
|
||||
package org.signal.chat.purchase;
|
||||
|
||||
import "org/signal/chat/common.proto";
|
||||
import "org/signal/chat/require.proto";
|
||||
import "org/signal/chat/tag.proto";
|
||||
import "org/signal/chat/subscriptions.proto";
|
||||
|
||||
// Retrieve product metadata for one-time donations, subscriptions, and backups
|
||||
service ProductConfiguration {
|
||||
option (require.auth) = AUTH_ONLY_AUTHENTICATED;
|
||||
|
||||
// Returns all configuration for badges, donation subscriptions, backup subscriptions, and one-time donation (
|
||||
// "boost" and "gift") minimum and suggested amounts.
|
||||
//
|
||||
// Product descriptions may contain localized strings. Callers should set
|
||||
// their language preferences via an "Accept-Language" header on the request
|
||||
// https://datatracker.ietf.org/doc/html/rfc3282#section-3
|
||||
rpc GetConfiguration(GetConfigurationRequest) returns (GetConfigurationResponse) {}
|
||||
}
|
||||
|
||||
message GetConfigurationRequest {
|
||||
// If present, the etag from a prior GetConfigurationResponse. If the
|
||||
// provided etag matches the current configuration etag, the server may elide
|
||||
// the configuration response.
|
||||
bytes etag = 1;
|
||||
}
|
||||
|
||||
message GetConfigurationResponse {
|
||||
oneof response {
|
||||
// The full configuration and corresponding ETag.
|
||||
TaggedConfiguration tagged_configuration = 1;
|
||||
|
||||
// The etag in the request matched the current configuration ETag
|
||||
bool etag_matched = 2 [(tag.reason) = "etag_match"];
|
||||
}
|
||||
}
|
||||
|
||||
message AmountList {
|
||||
// NOTE: this is a string instead of a numeric type because it is intended
|
||||
// for display purposes only
|
||||
repeated string amounts = 1;
|
||||
}
|
||||
|
||||
message CurrencyConfiguration {
|
||||
// Minimum one-time donation
|
||||
// NOTE: this is a string instead of a numeric type because it is intended
|
||||
// for display purposes only
|
||||
string minimum = 1;
|
||||
// Map of one-time donation level IDs to suggested amounts
|
||||
map<uint64, AmountList> one_time = 2;
|
||||
// Map of subscription level IDs to the amount charged
|
||||
map<uint64, string> subscription = 3;
|
||||
// Map of backup subscription level IDs to the amount charged
|
||||
map<uint64, string> backup_subscription = 4;
|
||||
repeated PaymentMethod supported_payment_methods = 5;
|
||||
}
|
||||
|
||||
message LevelConfiguration {
|
||||
common.Badge badge = 1;
|
||||
|
||||
// The duration for which a badge is valid. Present only for
|
||||
// one-time (boost, gift) badges
|
||||
optional uint64 badge_duration_seconds = 2;
|
||||
}
|
||||
|
||||
// Configuration for a backup level - use to present appropriate client interfaces
|
||||
message BackupLevelConfiguration {
|
||||
// The amount of media storage in bytes that a paying subscriber may store
|
||||
uint64 storage_allowance_bytes = 1;
|
||||
// The play billing productID associated with this backup level
|
||||
string play_product_id = 2;
|
||||
// The duration, in days, for which your backed up media is retained on the server after you stop refreshing with a paid credential
|
||||
uint64 media_ttl_days = 3;
|
||||
}
|
||||
|
||||
message BackupConfiguration {
|
||||
// A map of numeric backup level IDs to level-specific backup configuration
|
||||
map<uint64, BackupLevelConfiguration> levels = 1;
|
||||
// The number of days of media a free tier backup user gets
|
||||
uint64 free_tier_media_days = 2;
|
||||
}
|
||||
|
||||
message Configuration {
|
||||
// Map of lower-cased ISO 3 currency codes to currency-specific configuration
|
||||
map<string, CurrencyConfiguration> currencies = 1;
|
||||
// Map of numeric donation level IDs to level-specific badge configuration
|
||||
map<uint64, LevelConfiguration> badge_levels = 2;
|
||||
// Configuration for backup subscription options
|
||||
BackupConfiguration backup = 3;
|
||||
// Maximum value of a one-time SEPA donation
|
||||
string sepa_maximum_euros = 4;
|
||||
}
|
||||
|
||||
message TaggedConfiguration {
|
||||
Configuration configuration = 1;
|
||||
|
||||
// An entity tag for `configuration`. This may be used in subsequent
|
||||
// requests for the configuration version to optimize bandwidth.
|
||||
bytes etag = 2;
|
||||
}
|
||||
@@ -7,7 +7,7 @@ syntax = "proto3";
|
||||
|
||||
option java_multiple_files = true;
|
||||
|
||||
package org.signal.chat.subscriptions;
|
||||
package org.signal.chat.purchase;
|
||||
|
||||
import "google/protobuf/empty.proto";
|
||||
import "org/signal/chat/common.proto";
|
||||
@@ -15,6 +15,9 @@ import "org/signal/chat/require.proto";
|
||||
import "org/signal/chat/errors.proto";
|
||||
import "org/signal/chat/tag.proto";
|
||||
|
||||
// Service for creating donation subscriptions
|
||||
//
|
||||
// Configuration for subscription levels can be found in ProductConfiguration.
|
||||
service Subscriptions {
|
||||
option (require.auth) = AUTH_ONLY_ANONYMOUS;
|
||||
// Creates a subscriber record if it does not exist, otherwise refreshes its last access time.
|
||||
@@ -99,10 +102,6 @@ service Subscriptions {
|
||||
// associated with the old purchaseToken will be cancelled.
|
||||
rpc SetIapSubscription(SetIapSubscriptionRequest) returns (SetIapSubscriptionResponse) {}
|
||||
|
||||
// Returns all configuration for badges, donation subscriptions, backup subscriptions, and one-time donation (
|
||||
// "boost" and "gift") minimum and suggested amounts.
|
||||
rpc GetConfiguration(GetConfigurationRequest) returns (GetConfigurationResponse) {}
|
||||
|
||||
// Returns a localized bank mandate for the specified bank transfer type
|
||||
rpc GetBankMandate(GetBankMandateRequest) returns (GetBankMandateResponse) {}
|
||||
}
|
||||
@@ -252,6 +251,8 @@ message SetDefaultPaymentMethodResponse {
|
||||
// subscriberId authentication failure
|
||||
errors.FailedUnidentifiedAuthorization subscriber_id_mismatch = 3 [(tag.reason) = "subscriber_id_mismatch"];
|
||||
errors.FailedPrecondition payment_method_not_set_up = 4 [(tag.reason) = "payment_method_not_set_up"];
|
||||
// Payment processor does not match existing processor associated with the subscription
|
||||
errors.FailedPrecondition subscription_processor_conflict = 5 [(tag.reason) = "subscription_processor_conflict"];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -426,65 +427,6 @@ message GetSubscriptionInformationResponse {
|
||||
}
|
||||
}
|
||||
|
||||
message GetConfigurationRequest {}
|
||||
|
||||
message GetConfigurationResponse {
|
||||
message Badge {
|
||||
common.Badge badge = 1;
|
||||
// Present only for one-time (purchasable) badges
|
||||
optional uint64 duration_seconds = 2;
|
||||
}
|
||||
|
||||
message AmountList {
|
||||
// NOTE: this is a string instead of a numeric type because it is intended
|
||||
// for display purposes only
|
||||
repeated string amounts = 1;
|
||||
}
|
||||
|
||||
message CurrencyConfiguration {
|
||||
// Minimum one-time donation
|
||||
// NOTE: this is a string instead of a numeric type because it is intended
|
||||
// for display purposes only
|
||||
string minimum = 1;
|
||||
// Map of one-time donation level IDs to suggested amounts
|
||||
map<uint64, AmountList> one_time = 2;
|
||||
// Map of subscription level IDs to the amount charged
|
||||
map<uint64, string> subscription = 3;
|
||||
// Map of backup subscription level IDs to the amount charged
|
||||
map<uint64, string> backup_subscription = 4;
|
||||
repeated PaymentMethod supported_payment_methods = 5;
|
||||
}
|
||||
|
||||
message LevelConfiguration {
|
||||
Badge badge = 1;
|
||||
}
|
||||
|
||||
// Configuration for a backup level - use to present appropriate client interfaces
|
||||
message BackupLevelConfiguration {
|
||||
// The amount of media storage in bytes that a paying subscriber may store
|
||||
uint64 storage_allowance_bytes = 1;
|
||||
// The play billing productID associated with this backup level
|
||||
string play_product_id = 2;
|
||||
// The duration, in days, for which your backed up media is retained on the server after you stop refreshing with a paid credential
|
||||
uint64 media_ttl_days = 3;
|
||||
}
|
||||
|
||||
message BackupConfiguration {
|
||||
// A map of numeric backup level IDs to level-specific backup configuration
|
||||
map<uint64, BackupLevelConfiguration> levels = 1;
|
||||
// The number of days of media a free tier backup user gets
|
||||
uint64 free_tier_media_days = 2;
|
||||
}
|
||||
|
||||
// Map of lower-cased ISO 3 currency codes to currency-specific configuration
|
||||
map<string, CurrencyConfiguration> currencies = 1;
|
||||
// Map of numeric donation level IDs to level-specific badge configuration
|
||||
map<uint64, LevelConfiguration> levels = 2;
|
||||
BackupConfiguration backup = 3;
|
||||
// Maximum value of a one-time SEPA donation
|
||||
string sepa_maximum_euros = 4;
|
||||
}
|
||||
|
||||
enum BankTransferType {
|
||||
BANK_TRANSFER_TYPE_UNKNOWN = 0;
|
||||
BANK_TRANSFER_TYPE_SEPA_DEBIT = 1;
|
||||
|
||||
+3
-10
@@ -72,14 +72,12 @@ 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.BackupConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.SecureValueRecoveryConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicBackupConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecoveryClient;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamoDbExtension;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamoDbExtensionSchema;
|
||||
import org.whispersystems.textsecuregcm.util.AttributeValues;
|
||||
@@ -114,7 +112,7 @@ public class BackupManagerTest {
|
||||
private final RemoteStorageManager remoteStorageManager = mock(RemoteStorageManager.class);
|
||||
private final byte[] backupKey = TestRandomUtil.nextBytes(32);
|
||||
private final UUID aci = UUID.randomUUID();
|
||||
private final DynamicBackupConfiguration backupConfiguration = new DynamicBackupConfiguration(
|
||||
private final BackupConfiguration backupConfiguration = new BackupConfiguration(
|
||||
3, 4, 5, Duration.ofSeconds(30), MAX_TOTAL_MEDIA_BYTES);
|
||||
|
||||
|
||||
@@ -146,11 +144,6 @@ public class BackupManagerTest {
|
||||
DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(),
|
||||
DynamoDbExtensionSchema.Tables.BACKUPS.tableName(),
|
||||
testClock);
|
||||
@SuppressWarnings("unchecked") final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager =
|
||||
mock(DynamicConfigurationManager.class);
|
||||
final DynamicConfiguration dynamicConfiguration = mock(DynamicConfiguration.class);
|
||||
when(dynamicConfiguration.getBackupConfiguration()).thenReturn(backupConfiguration);
|
||||
when(dynamicConfigurationManager.getConfiguration()).thenReturn(dynamicConfiguration);
|
||||
|
||||
this.backupManager = new BackupManager(
|
||||
backupsDb,
|
||||
@@ -162,7 +155,7 @@ public class BackupManagerTest {
|
||||
svrbCredentialGenerator,
|
||||
svrbClient,
|
||||
testClock,
|
||||
dynamicConfigurationManager);
|
||||
backupConfiguration);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
|
||||
+15
-12
@@ -20,6 +20,7 @@ import io.dropwizard.testing.junit5.DropwizardExtensionsSupport;
|
||||
import io.dropwizard.testing.junit5.ResourceExtension;
|
||||
import jakarta.ws.rs.client.Entity;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import java.io.IOException;
|
||||
import java.time.Instant;
|
||||
import java.util.Base64;
|
||||
import java.util.Collections;
|
||||
@@ -55,6 +56,7 @@ import org.whispersystems.textsecuregcm.subscriptions.PaymentDetails;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentMethod;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentStatus;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidAmountException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorException;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
|
||||
import org.whispersystems.textsecuregcm.util.HeaderUtils;
|
||||
@@ -179,13 +181,13 @@ class OneTimeDonationControllerTest extends AbstractV1SubscriptionControllerTest
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void testCreateBoostPaymentIntent(final boolean donationPermitSpendOk) {
|
||||
void testCreateBoostPaymentIntent(final boolean donationPermitSpendOk) throws SubscriptionInvalidAmountException {
|
||||
when(DONATION_PERMITS.spend(any(byte[].class), any(Instant.class))).thenReturn(donationPermitSpendOk);
|
||||
|
||||
when(STRIPE_MANAGER.getSupportedCurrenciesForPaymentMethod(PaymentMethod.CARD))
|
||||
.thenReturn(Set.of("usd", "jpy", "bif", "eur"));
|
||||
when(STRIPE_MANAGER.createPaymentIntent(anyString(), anyLong(), anyLong(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(PAYMENT_INTENT));
|
||||
.thenReturn(PAYMENT_INTENT);
|
||||
|
||||
String clientSecret = "some_client_secret";
|
||||
when(PAYMENT_INTENT.getClientSecret()).thenReturn(clientSecret);
|
||||
@@ -202,13 +204,13 @@ class OneTimeDonationControllerTest extends AbstractV1SubscriptionControllerTest
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCreateBoostPayPal() {
|
||||
void testCreateBoostPayPal() throws IOException {
|
||||
final BraintreeManager.PayPalOneTimePaymentApprovalDetails payPalOneTimePaymentApprovalDetails = mock(
|
||||
BraintreeManager.PayPalOneTimePaymentApprovalDetails.class);
|
||||
when(BRAINTREE_MANAGER.getSupportedCurrenciesForPaymentMethod(PaymentMethod.PAYPAL))
|
||||
.thenReturn(Set.of("usd", "jpy", "bif", "eur"));
|
||||
when(BRAINTREE_MANAGER.createOneTimePayment(anyString(), anyLong(), anyString(), anyString(), anyString(), anyString()))
|
||||
.thenReturn(CompletableFuture.completedFuture(payPalOneTimePaymentApprovalDetails));
|
||||
.thenReturn(payPalOneTimePaymentApprovalDetails);
|
||||
when(payPalOneTimePaymentApprovalDetails.approvalUrl()).thenReturn("approvalUrl");
|
||||
when(payPalOneTimePaymentApprovalDetails.paymentId()).thenReturn("someId");
|
||||
|
||||
@@ -239,14 +241,15 @@ class OneTimeDonationControllerTest extends AbstractV1SubscriptionControllerTest
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void createBoostReceiptPaymentRequired(final ChargeFailure chargeFailure, boolean expectChargeFailure) {
|
||||
when(STRIPE_MANAGER.getPaymentDetails(any())).thenReturn(CompletableFuture.completedFuture(Optional.of(new PaymentDetails(
|
||||
void createBoostReceiptPaymentRequired(final ChargeFailure chargeFailure, boolean expectChargeFailure)
|
||||
throws IOException {
|
||||
when(STRIPE_MANAGER.getPaymentDetails(any())).thenReturn(Optional.of(new PaymentDetails(
|
||||
"id",
|
||||
Collections.emptyMap(),
|
||||
PaymentStatus.FAILED,
|
||||
Instant.now(),
|
||||
chargeFailure))
|
||||
));
|
||||
);
|
||||
try (Response response = RESOURCE_EXTENSION.target("/v1/subscription/boost/receipt_credentials")
|
||||
.request()
|
||||
.post(Entity.json("""
|
||||
@@ -281,13 +284,13 @@ class OneTimeDonationControllerTest extends AbstractV1SubscriptionControllerTest
|
||||
}
|
||||
|
||||
@Test
|
||||
void confirmPaypalBoostProcessorError() {
|
||||
void confirmPaypalBoostProcessorError() throws SubscriptionProcessorException, IOException {
|
||||
when(BRAINTREE_MANAGER.getSupportedCurrenciesForPaymentMethod(PaymentMethod.PAYPAL))
|
||||
.thenReturn(Set.of("usd", "jpy", "bif", "eur"));
|
||||
when(BRAINTREE_MANAGER.captureOneTimePayment(anyString(), anyString(), anyString(), anyString(), anyLong(),
|
||||
anyLong(), any()))
|
||||
.thenReturn(CompletableFuture.failedFuture(new SubscriptionProcessorException(PaymentProvider.BRAINTREE,
|
||||
new ChargeFailure("2046", "Declined", null, null, null))));
|
||||
.thenThrow(new SubscriptionProcessorException(PaymentProvider.BRAINTREE,
|
||||
new ChargeFailure("2046", "Declined", null, null, null)));
|
||||
|
||||
try (Response response = RESOURCE_EXTENSION.target("/v1/subscription/boost/paypal/confirm")
|
||||
.request()
|
||||
@@ -323,12 +326,12 @@ class OneTimeDonationControllerTest extends AbstractV1SubscriptionControllerTest
|
||||
ServerSecretParams.generate().getPublicParams()).createReceiptCredentialRequestContext(
|
||||
new ReceiptSerial(new byte[ReceiptSerial.SIZE])).getRequest();
|
||||
|
||||
when(STRIPE_MANAGER.getPaymentDetails(any())).thenReturn(CompletableFuture.completedFuture(Optional.of(new PaymentDetails(
|
||||
when(STRIPE_MANAGER.getPaymentDetails(any())).thenReturn(Optional.of(new PaymentDetails(
|
||||
"id",
|
||||
Collections.emptyMap(),
|
||||
PaymentStatus.SUCCEEDED,
|
||||
Instant.now(),
|
||||
null))));
|
||||
null)));
|
||||
doThrow(WriteConflictException.class).when(ISSUED_RECEIPTS_MANAGER).recordIssuance(any(), any(), any(), any());
|
||||
|
||||
try (Response response = RESOURCE_EXTENSION.target("/v1/subscription/boost/receipt_credentials")
|
||||
|
||||
+1
-9
@@ -61,15 +61,12 @@ import org.signal.libsignal.zkgroup.receipts.ServerZkReceiptOperations;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.badges.BadgeTranslator;
|
||||
import org.whispersystems.textsecuregcm.configuration.SubscriptionConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicBackupConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.controllers.SubscriptionController.GetBankMandateResponse;
|
||||
import org.whispersystems.textsecuregcm.controllers.SubscriptionController.GetSubscriptionConfigurationResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.Badge;
|
||||
import org.whispersystems.textsecuregcm.entities.BadgeSvg;
|
||||
import org.whispersystems.textsecuregcm.mappers.CompletionExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.SubscriptionExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.storage.PaymentTime;
|
||||
import org.whispersystems.textsecuregcm.storage.SubscriptionManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Subscriptions;
|
||||
@@ -112,12 +109,11 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest {
|
||||
private static final ServerZkReceiptOperations ZK_OPS = mock(ServerZkReceiptOperations.class);
|
||||
private static final BadgeTranslator BADGE_TRANSLATOR = mock(BadgeTranslator.class);
|
||||
private static final BankMandateTranslator BANK_MANDATE_TRANSLATOR = mock(BankMandateTranslator.class);
|
||||
private static final DynamicConfigurationManager<DynamicConfiguration> DYNAMIC_CONFIGURATION_MANAGER = mock(DynamicConfigurationManager.class);
|
||||
private final static SubscriptionController SUBSCRIPTION_CONTROLLER = new SubscriptionController(CLOCK,
|
||||
SUBSCRIPTION_CONFIG, ONETIME_CONFIG,
|
||||
new SubscriptionManager(SUBSCRIPTIONS, List.of(STRIPE_MANAGER, BRAINTREE_MANAGER, PLAY_MANAGER, APPSTORE_MANAGER),
|
||||
ZK_OPS, ISSUED_RECEIPTS_MANAGER), STRIPE_MANAGER, BRAINTREE_MANAGER, PLAY_MANAGER, APPSTORE_MANAGER,
|
||||
BADGE_TRANSLATOR, BANK_MANDATE_TRANSLATOR, DONATION_PERMITS_MANAGER, DYNAMIC_CONFIGURATION_MANAGER);
|
||||
BADGE_TRANSLATOR, BANK_MANDATE_TRANSLATOR, DONATION_PERMITS_MANAGER, MAX_TOTAL_BACKUP_MEDIA_BYTES);
|
||||
private static final ResourceExtension RESOURCE_EXTENSION = ResourceExtension.builder()
|
||||
.addProperty(ServerProperties.UNWRAP_COMPLETION_STAGE_IN_WRITER_ENABLE, Boolean.TRUE)
|
||||
.addProvider(AuthHelper.getAuthFilter())
|
||||
@@ -139,10 +135,6 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest {
|
||||
|
||||
when(STRIPE_MANAGER.getProvider()).thenReturn(PaymentProvider.STRIPE);
|
||||
when(BRAINTREE_MANAGER.getProvider()).thenReturn(PaymentProvider.BRAINTREE);
|
||||
final DynamicConfiguration dynamicConfiguration = mock(DynamicConfiguration.class);
|
||||
when(dynamicConfiguration.getBackupConfiguration())
|
||||
.thenReturn(new DynamicBackupConfiguration(null, null, null, null, MAX_TOTAL_BACKUP_MEDIA_BYTES));
|
||||
when(DYNAMIC_CONFIGURATION_MANAGER.getConfiguration()).thenReturn(dynamicConfiguration);
|
||||
|
||||
List.of(STRIPE_MANAGER, BRAINTREE_MANAGER)
|
||||
.forEach(manager -> when(manager.supportsPaymentMethod(any()))
|
||||
|
||||
+3
@@ -121,12 +121,14 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
|
||||
PhoneNumberUtil.getInstance().getExampleNumber("US"), PhoneNumberUtil.PhoneNumberFormat.E164);
|
||||
|
||||
final byte[] usernameHash = TestRandomUtil.nextBytes(32);
|
||||
final UUID usernameLinkHandle = UUID.randomUUID();
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
when(account.getUuid()).thenReturn(AUTHENTICATED_ACI);
|
||||
when(account.getPhoneNumberIdentifier()).thenReturn(phoneNumberIdentifier);
|
||||
when(account.getNumber()).thenReturn(e164);
|
||||
when(account.getUsernameHash()).thenReturn(Optional.of(usernameHash));
|
||||
when(account.getUsernameLinkHandle()).thenReturn(usernameLinkHandle);
|
||||
|
||||
when(accountsManager.getByAccountIdentifier(AUTHENTICATED_ACI))
|
||||
.thenReturn(Optional.of(account));
|
||||
@@ -137,6 +139,7 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
|
||||
.addServiceIdentifiers(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(new PniServiceIdentifier(phoneNumberIdentifier)))
|
||||
.setE164(e164)
|
||||
.setUsernameHash(ByteString.copyFrom(usernameHash))
|
||||
.setUsernameLinkHandle(UUIDUtil.toByteString(usernameLinkHandle))
|
||||
.build())
|
||||
.build();
|
||||
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import com.google.protobuf.Any;
|
||||
import com.google.rpc.ErrorInfo;
|
||||
import io.grpc.StatusRuntimeException;
|
||||
import io.grpc.protobuf.StatusProto;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.signal.chat.common.IdentityType;
|
||||
import org.signal.chat.common.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
|
||||
class GrpcExceptionsTest {
|
||||
|
||||
@Test
|
||||
void streamClosed() {
|
||||
final ServiceIdentifier message = ServiceIdentifier.newBuilder().setIdentityType(IdentityType.IDENTITY_TYPE_ACI)
|
||||
.setUuid(UUIDUtil.toByteString(UUID.randomUUID()))
|
||||
.build();
|
||||
final StatusRuntimeException statusRuntimeException = GrpcExceptions.streamClosed(message);
|
||||
final com.google.rpc.Status status = StatusProto.fromThrowable(statusRuntimeException);
|
||||
final List<Any> details = status.getDetailsList();
|
||||
assertEquals(2, details.size());
|
||||
assertEquals(1, details.stream().filter(any -> any.is(ErrorInfo.class)).count());
|
||||
|
||||
final Any packed = details.stream().filter(any -> any.is(ServiceIdentifier.class)).findFirst().orElseThrow();
|
||||
assertEquals("type.googleapis.com/org.signal.chat.common.ServiceIdentifier", packed.getTypeUrl(), """
|
||||
The generated typeUrl for a packed Any message has changed. gRPC clients may rely on stable typeUrls
|
||||
scheme to distinguish `details` in error metadata
|
||||
""");
|
||||
}
|
||||
}
|
||||
+26
-24
@@ -18,30 +18,30 @@ import com.google.common.net.InetAddresses;
|
||||
import com.google.protobuf.ByteString;
|
||||
import com.stripe.model.PaymentIntent;
|
||||
import jakarta.annotation.Nullable;
|
||||
import java.io.IOException;
|
||||
import java.time.Instant;
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.stream.Stream;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.mockito.Mock;
|
||||
import org.signal.chat.one_time_donations.ConfirmPayPalBoostRequest;
|
||||
import org.signal.chat.one_time_donations.ConfirmPayPalBoostResponse;
|
||||
import org.signal.chat.one_time_donations.CreateBoostReceiptCredentialsRequest;
|
||||
import org.signal.chat.one_time_donations.CreateBoostReceiptCredentialsResponse;
|
||||
import org.signal.chat.one_time_donations.CreateBoostRequest;
|
||||
import org.signal.chat.one_time_donations.CreateBoostResponse;
|
||||
import org.signal.chat.one_time_donations.CreatePayPalBoostRequest;
|
||||
import org.signal.chat.one_time_donations.CreatePayPalBoostResponse;
|
||||
import org.signal.chat.one_time_donations.OneTimeDonationsGrpc;
|
||||
import org.signal.chat.subscriptions.PaymentMethod;
|
||||
import org.signal.chat.subscriptions.PaymentProvider;
|
||||
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.OneTimeDonationsGrpc;
|
||||
import org.signal.chat.purchase.PaymentMethod;
|
||||
import org.signal.chat.purchase.PaymentProvider;
|
||||
import org.signal.libsignal.zkgroup.ServerSecretParams;
|
||||
import org.signal.libsignal.zkgroup.VerificationFailedException;
|
||||
import org.signal.libsignal.zkgroup.donation.DonationPermit;
|
||||
@@ -66,6 +66,8 @@ import org.whispersystems.textsecuregcm.subscriptions.PayPalDonationsTranslator;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentDetails;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentStatus;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.StripeManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidAmountException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorException;
|
||||
import org.whispersystems.textsecuregcm.tests.util.SubscriptionConfigTestHelper;
|
||||
import org.whispersystems.textsecuregcm.util.TestClock;
|
||||
|
||||
@@ -135,14 +137,14 @@ public class OneTimeDonationsGrpcServiceTest extends
|
||||
}
|
||||
|
||||
@Test
|
||||
void createBoost() {
|
||||
void createBoost() throws SubscriptionInvalidAmountException {
|
||||
final PaymentIntent paymentIntent = mock(PaymentIntent.class);
|
||||
when(paymentIntent.getClientSecret()).thenReturn("test-client-secret");
|
||||
when(stripeManager.getSupportedCurrenciesForPaymentMethod(
|
||||
org.whispersystems.textsecuregcm.subscriptions.PaymentMethod.CARD))
|
||||
.thenReturn(Set.of("usd"));
|
||||
when(stripeManager.createPaymentIntent(any(), anyLong(), anyLong(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(paymentIntent));
|
||||
.thenReturn(paymentIntent);
|
||||
|
||||
final CreateBoostResponse response = unauthenticatedServiceStub().createBoost(
|
||||
CreateBoostRequest.newBuilder()
|
||||
@@ -212,7 +214,7 @@ public class OneTimeDonationsGrpcServiceTest extends
|
||||
}
|
||||
|
||||
@Test
|
||||
void createPayPalBoost() {
|
||||
void createPayPalBoost() throws IOException {
|
||||
final BraintreeManager.PayPalOneTimePaymentApprovalDetails approvalDetails =
|
||||
mock(BraintreeManager.PayPalOneTimePaymentApprovalDetails.class);
|
||||
when(approvalDetails.approvalUrl()).thenReturn("test-approval-url");
|
||||
@@ -224,7 +226,7 @@ public class OneTimeDonationsGrpcServiceTest extends
|
||||
.thenReturn("Donation to Signal Technology Foundation");
|
||||
when(braintreeManager.createOneTimePayment(anyString(), anyLong(), anyString(), anyString(), anyString(),
|
||||
anyString()))
|
||||
.thenReturn(CompletableFuture.completedFuture(approvalDetails));
|
||||
.thenReturn(approvalDetails);
|
||||
|
||||
final CreatePayPalBoostResponse response = unauthenticatedServiceStub().createPayPalBoost(
|
||||
CreatePayPalBoostRequest.newBuilder()
|
||||
@@ -241,14 +243,14 @@ public class OneTimeDonationsGrpcServiceTest extends
|
||||
}
|
||||
|
||||
@Test
|
||||
void confirmPayPalBoost() {
|
||||
void confirmPayPalBoost() throws SubscriptionProcessorException, IOException {
|
||||
when(braintreeManager.getSupportedCurrenciesForPaymentMethod(
|
||||
org.whispersystems.textsecuregcm.subscriptions.PaymentMethod.PAYPAL))
|
||||
.thenReturn(Set.of("usd"));
|
||||
when(braintreeManager.captureOneTimePayment(anyString(), anyString(), anyString(), anyString(), anyLong(),
|
||||
anyLong(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(
|
||||
new BraintreeManager.PayPalChargeSuccessDetails("test-id")));
|
||||
.thenReturn(
|
||||
new BraintreeManager.PayPalChargeSuccessDetails("test-id"));
|
||||
|
||||
final ConfirmPayPalBoostResponse response = unauthenticatedServiceStub().confirmPayPalBoost(
|
||||
ConfirmPayPalBoostRequest.newBuilder()
|
||||
@@ -268,10 +270,10 @@ public class OneTimeDonationsGrpcServiceTest extends
|
||||
@MethodSource
|
||||
void createBoostReceiptCredentialsPaymentRequired(
|
||||
@Nullable final ChargeFailure chargeFailure,
|
||||
final boolean expectChargeFailure) {
|
||||
when(stripeManager.getPaymentDetails(any())).thenReturn(CompletableFuture.completedFuture(
|
||||
final boolean expectChargeFailure) throws IOException {
|
||||
when(stripeManager.getPaymentDetails(any())).thenReturn(
|
||||
Optional.of(new PaymentDetails("id", Collections.emptyMap(), PaymentStatus.FAILED,
|
||||
clock.instant(), chargeFailure))));
|
||||
clock.instant(), chargeFailure)));
|
||||
|
||||
final CreateBoostReceiptCredentialsResponse response =
|
||||
unauthenticatedServiceStub().createBoostReceiptCredentials(
|
||||
@@ -303,9 +305,9 @@ public class OneTimeDonationsGrpcServiceTest extends
|
||||
ServerSecretParams.generate().getPublicParams()).createReceiptCredentialRequestContext(
|
||||
new ReceiptSerial(new byte[ReceiptSerial.SIZE])).getRequest();
|
||||
|
||||
when(stripeManager.getPaymentDetails(any())).thenReturn(CompletableFuture.completedFuture(
|
||||
when(stripeManager.getPaymentDetails(any())).thenReturn(
|
||||
Optional.of(new PaymentDetails("id", Collections.emptyMap(), PaymentStatus.SUCCEEDED,
|
||||
clock.instant(), null))));
|
||||
clock.instant(), null)));
|
||||
doThrow(WriteConflictException.class).when(issuedReceiptsManager)
|
||||
.recordIssuance(any(), any(), any(), any());
|
||||
|
||||
|
||||
+220
@@ -0,0 +1,220 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.google.common.net.InetAddresses;
|
||||
import com.google.protobuf.ByteString;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mock;
|
||||
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.PaymentMethod;
|
||||
import org.signal.chat.purchase.ProductConfigurationGrpc;
|
||||
import org.whispersystems.textsecuregcm.badges.BadgeTranslator;
|
||||
import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.SubscriptionConfiguration;
|
||||
import org.whispersystems.textsecuregcm.entities.Badge;
|
||||
import org.whispersystems.textsecuregcm.entities.BadgeSvg;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.BraintreeManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.StripeManager;
|
||||
import org.whispersystems.textsecuregcm.tests.util.SubscriptionConfigTestHelper;
|
||||
|
||||
public class ProductConfigurationGrpcServiceTest extends
|
||||
SimpleBaseGrpcTest<ProductConfigurationGrpcService, ProductConfigurationGrpc.ProductConfigurationBlockingStub> {
|
||||
|
||||
private final SubscriptionConfiguration subscriptionConfiguration =
|
||||
SubscriptionConfigTestHelper.getSubscriptionConfig();
|
||||
|
||||
private final OneTimeDonationConfiguration oneTimeDonationConfiguration =
|
||||
SubscriptionConfigTestHelper.getOneTimeConfig();
|
||||
|
||||
@Mock
|
||||
private StripeManager stripeManager;
|
||||
|
||||
@Mock
|
||||
private BraintreeManager braintreeManager;
|
||||
|
||||
@Mock
|
||||
private BadgeTranslator badgeTranslator;
|
||||
|
||||
@Override
|
||||
protected ProductConfigurationGrpcService createServiceBeforeEachTest() {
|
||||
getMockRequestAttributesInterceptor().setRequestAttributes(
|
||||
new RequestAttributes(InetAddresses.forString("127.0.0.1"), null, "en-us"));
|
||||
|
||||
when(stripeManager.supportsPaymentMethod(any())).thenCallRealMethod();
|
||||
when(stripeManager.getSupportedCurrenciesForPaymentMethod(
|
||||
org.whispersystems.textsecuregcm.subscriptions.PaymentMethod.CARD))
|
||||
.thenReturn(Set.of("usd", "jpy", "bif", "eur"));
|
||||
when(stripeManager.getSupportedCurrenciesForPaymentMethod(
|
||||
org.whispersystems.textsecuregcm.subscriptions.PaymentMethod.SEPA_DEBIT))
|
||||
.thenReturn(Set.of("eur"));
|
||||
when(stripeManager.getSupportedCurrenciesForPaymentMethod(
|
||||
org.whispersystems.textsecuregcm.subscriptions.PaymentMethod.IDEAL))
|
||||
.thenReturn(Set.of("eur"));
|
||||
when(braintreeManager.supportsPaymentMethod(any())).thenCallRealMethod();
|
||||
when(braintreeManager.getSupportedCurrenciesForPaymentMethod(
|
||||
org.whispersystems.textsecuregcm.subscriptions.PaymentMethod.PAYPAL))
|
||||
.thenReturn(Set.of("usd", "jpy"));
|
||||
|
||||
when(badgeTranslator.translate(any(), eq("B1"))).thenReturn(new Badge("B1", "cat1", "name1", "desc1",
|
||||
List.of("l", "m", "h", "x", "xx", "xxx"), "SVG", List.of(new BadgeSvg("sl", "sd"))));
|
||||
when(badgeTranslator.translate(any(), eq("B2"))).thenReturn(new Badge("B2", "cat2", "name2", "desc2",
|
||||
List.of("l", "m", "h", "x", "xx", "xxx"), "SVG", List.of(new BadgeSvg("sl", "sd"))));
|
||||
when(badgeTranslator.translate(any(), eq("B3"))).thenReturn(new Badge("B3", "cat3", "name3", "desc3",
|
||||
List.of("l", "m", "h", "x", "xx", "xxx"), "SVG", List.of(new BadgeSvg("sl", "sd"))));
|
||||
when(badgeTranslator.translate(any(), eq("BOOST"))).thenReturn(new Badge("BOOST", "boost1", "boost1", "boost1",
|
||||
List.of("l", "m", "h", "x", "xx", "xxx"), "SVG", List.of(new BadgeSvg("sl", "sd"))));
|
||||
when(badgeTranslator.translate(any(), eq("GIFT"))).thenReturn(new Badge("GIFT", "gift1", "gift1", "gift1",
|
||||
List.of("l", "m", "h", "x", "xx", "xxx"), "SVG", List.of(new BadgeSvg("sl", "sd"))));
|
||||
|
||||
when(badgeTranslator.resolveLocale(any())).thenReturn(Locale.US);
|
||||
|
||||
|
||||
return new ProductConfigurationGrpcService(subscriptionConfiguration, oneTimeDonationConfiguration,
|
||||
List.of(stripeManager, braintreeManager), badgeTranslator, 1234L);
|
||||
}
|
||||
|
||||
private void checkConfiguration(final Configuration configuration) {
|
||||
assertEquals("10000", configuration.getSepaMaximumEuros());
|
||||
|
||||
assertEquals(30L, configuration.getBackup().getFreeTierMediaDays());
|
||||
final BackupLevelConfiguration backupLevel =
|
||||
configuration.getBackup().getLevelsOrThrow(201L);
|
||||
assertEquals(1234L, backupLevel.getStorageAllowanceBytes());
|
||||
assertEquals("testPlayProductId", backupLevel.getPlayProductId());
|
||||
assertEquals(40L, backupLevel.getMediaTtlDays());
|
||||
|
||||
final CurrencyConfiguration usd = configuration.getCurrenciesOrThrow("usd");
|
||||
assertEquals("2.50", usd.getMinimum());
|
||||
assertEquals(List.of(PaymentMethod.PAYMENT_METHOD_CARD, PaymentMethod.PAYMENT_METHOD_PAYPAL),
|
||||
usd.getSupportedPaymentMethodsList());
|
||||
assertEquals(List.of("5.50", "6", "7", "8", "9", "10"), usd.getOneTimeOrThrow(1L).getAmountsList());
|
||||
assertEquals(List.of("20"), usd.getOneTimeOrThrow(100L).getAmountsList());
|
||||
assertEquals(Map.of(5L, "5", 15L, "15", 35L, "35"), usd.getSubscriptionMap());
|
||||
assertEquals(Map.of(201L, "5"), usd.getBackupSubscriptionMap());
|
||||
|
||||
final CurrencyConfiguration jpy = configuration.getCurrenciesOrThrow("jpy");
|
||||
assertEquals("250", jpy.getMinimum());
|
||||
assertEquals(List.of(PaymentMethod.PAYMENT_METHOD_CARD, PaymentMethod.PAYMENT_METHOD_PAYPAL),
|
||||
jpy.getSupportedPaymentMethodsList());
|
||||
assertEquals(List.of("550", "600", "700", "800", "900", "1000"), jpy.getOneTimeOrThrow(1L).getAmountsList());
|
||||
assertEquals(List.of("2000"), jpy.getOneTimeOrThrow(100L).getAmountsList());
|
||||
assertEquals(Map.of(5L, "500", 15L, "1500", 35L, "3500"), jpy.getSubscriptionMap());
|
||||
assertEquals(Map.of(201L, "500"), jpy.getBackupSubscriptionMap());
|
||||
|
||||
final CurrencyConfiguration bif = configuration.getCurrenciesOrThrow("bif");
|
||||
assertEquals("2500", bif.getMinimum());
|
||||
assertEquals(List.of(PaymentMethod.PAYMENT_METHOD_CARD), bif.getSupportedPaymentMethodsList());
|
||||
assertEquals(List.of("5500", "6000", "7000", "8000", "9000", "10000"), bif.getOneTimeOrThrow(1L).getAmountsList());
|
||||
assertEquals(List.of("20000"), bif.getOneTimeOrThrow(100L).getAmountsList());
|
||||
assertEquals(Map.of(5L, "5000", 15L, "15000", 35L, "35000"), bif.getSubscriptionMap());
|
||||
assertEquals(Map.of(201L, "5000"), bif.getBackupSubscriptionMap());
|
||||
|
||||
final CurrencyConfiguration eur = configuration.getCurrenciesOrThrow("eur");
|
||||
assertEquals("3", eur.getMinimum());
|
||||
assertEquals(
|
||||
List.of(PaymentMethod.PAYMENT_METHOD_CARD, PaymentMethod.PAYMENT_METHOD_SEPA_DEBIT,
|
||||
PaymentMethod.PAYMENT_METHOD_IDEAL),
|
||||
eur.getSupportedPaymentMethodsList());
|
||||
assertEquals(List.of("5", "10", "20", "30", "50", "100"), eur.getOneTimeOrThrow(1L).getAmountsList());
|
||||
assertEquals(List.of("5"), eur.getOneTimeOrThrow(100L).getAmountsList());
|
||||
assertEquals(Map.of(5L, "5", 15L, "15", 35L, "35"), eur.getSubscriptionMap());
|
||||
assertEquals(Map.of(201L, "5"), eur.getBackupSubscriptionMap());
|
||||
|
||||
assertEquals("B1", configuration.getBadgeLevelsOrThrow(5L).getBadge().getId());
|
||||
assertEquals(0L, configuration.getBadgeLevelsOrThrow(5L).getBadgeDurationSeconds());
|
||||
assertEquals("B2", configuration.getBadgeLevelsOrThrow(15L).getBadge().getId());
|
||||
assertEquals("B3", configuration.getBadgeLevelsOrThrow(35L).getBadge().getId());
|
||||
assertEquals("BOOST", configuration.getBadgeLevelsOrThrow(1L).getBadge().getId());
|
||||
assertTrue(configuration.getBadgeLevelsOrThrow(1L).getBadgeDurationSeconds() > 0);
|
||||
assertEquals("GIFT", configuration.getBadgeLevelsOrThrow(100L).getBadge().getId());
|
||||
assertTrue(configuration.getBadgeLevelsOrThrow(100L).getBadgeDurationSeconds() > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getConfigurationNoEtag() {
|
||||
final GetConfigurationResponse response = unauthenticatedServiceStub()
|
||||
.getConfiguration(GetConfigurationRequest.newBuilder().build());
|
||||
|
||||
assertFalse(response.hasEtagMatched());
|
||||
checkConfiguration(response.getTaggedConfiguration().getConfiguration());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getConfigurationWrongEtag() {
|
||||
final GetConfigurationResponse response = unauthenticatedServiceStub()
|
||||
.getConfiguration(GetConfigurationRequest.newBuilder().setEtag(ByteString.copyFrom(new byte[32])).build());
|
||||
assertFalse(response.hasEtagMatched());
|
||||
checkConfiguration(response.getTaggedConfiguration().getConfiguration());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getConfigurationCorrectEtag() {
|
||||
final GetConfigurationResponse response = unauthenticatedServiceStub()
|
||||
.getConfiguration(GetConfigurationRequest.newBuilder().build());
|
||||
final ByteString etag = response.getTaggedConfiguration().getEtag();
|
||||
|
||||
final GetConfigurationResponse withCorrectEtag = unauthenticatedServiceStub()
|
||||
.getConfiguration(GetConfigurationRequest.newBuilder().setEtag(etag).build());
|
||||
assertTrue(withCorrectEtag.hasEtagMatched());
|
||||
assertTrue(withCorrectEtag.getEtagMatched());
|
||||
assertFalse(withCorrectEtag.hasTaggedConfiguration());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getConfigurationComputesOnce() {
|
||||
final RequestAttributes frAttributes =
|
||||
new RequestAttributes(InetAddresses.forString("127.0.0.1"), null, "fr-fr");
|
||||
final List<Locale> frLocales = List.of(Locale.FRANCE);
|
||||
final RequestAttributes caAttributes =
|
||||
new RequestAttributes(InetAddresses.forString("127.0.0.1"), null, "en-ca");
|
||||
final List<Locale> caLocales = List.of(Locale.CANADA);
|
||||
|
||||
when(badgeTranslator.resolveLocale(frLocales)).thenReturn(Locale.FRANCE);
|
||||
when(badgeTranslator.resolveLocale(caLocales)).thenReturn(Locale.CANADA);
|
||||
|
||||
// return slightly different values based on the language so the two configurations have different etags
|
||||
when(badgeTranslator.translate(eq(frLocales), eq("B1")))
|
||||
.thenReturn(new Badge("B1", "cat1", "name1", "desc1", List.of("l", "m", "h", "x", "xx", "xxx"), "SVG", List.of(new BadgeSvg("sl", "sd"))));
|
||||
when(badgeTranslator.translate(eq(caLocales), eq("B1")))
|
||||
.thenReturn(new Badge("B1", "dog1", "name1", "desc1", List.of("l", "m", "h", "x", "xx", "xxx"), "SVG", List.of(new BadgeSvg("sl", "sd"))));
|
||||
|
||||
getMockRequestAttributesInterceptor().setRequestAttributes(caAttributes);
|
||||
final GetConfigurationResponse caResponse =
|
||||
unauthenticatedServiceStub().getConfiguration(GetConfigurationRequest.newBuilder().build());
|
||||
final GetConfigurationResponse caResponseCached = unauthenticatedServiceStub()
|
||||
.getConfiguration(GetConfigurationRequest.newBuilder()
|
||||
.setEtag(caResponse.getTaggedConfiguration().getEtag())
|
||||
.build());
|
||||
assertTrue(caResponseCached.hasEtagMatched());
|
||||
verify(badgeTranslator, times(1)).translate(any(), eq("B1"));
|
||||
|
||||
getMockRequestAttributesInterceptor().setRequestAttributes(frAttributes);
|
||||
final GetConfigurationResponse frResponse =
|
||||
unauthenticatedServiceStub().getConfiguration(GetConfigurationRequest.newBuilder().build());
|
||||
assertFalse(frResponse.hasEtagMatched());
|
||||
verify(badgeTranslator, times(2)).translate(any(), eq("B1"));
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
+33
-144
@@ -19,12 +19,12 @@ import static org.mockito.Mockito.when;
|
||||
|
||||
import com.google.common.net.InetAddresses;
|
||||
import com.google.protobuf.ByteString;
|
||||
import java.io.IOException;
|
||||
import java.math.BigDecimal;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
@@ -35,30 +35,28 @@ import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.EnumSource;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.mockito.Mock;
|
||||
import org.signal.chat.subscriptions.CreatePayPalPaymentMethodRequest;
|
||||
import org.signal.chat.subscriptions.CreatePayPalPaymentMethodResponse;
|
||||
import org.signal.chat.subscriptions.CreatePaymentMethodRequest;
|
||||
import org.signal.chat.subscriptions.CreatePaymentMethodResponse;
|
||||
import org.signal.chat.subscriptions.DeleteSubscriberRequest;
|
||||
import org.signal.chat.subscriptions.DeleteSubscriberResponse;
|
||||
import org.signal.chat.subscriptions.GetBankMandateRequest;
|
||||
import org.signal.chat.subscriptions.GetBankMandateResponse;
|
||||
import org.signal.chat.subscriptions.GetConfigurationRequest;
|
||||
import org.signal.chat.subscriptions.GetConfigurationResponse;
|
||||
import org.signal.chat.subscriptions.GetReceiptCredentialsRequest;
|
||||
import org.signal.chat.subscriptions.GetReceiptCredentialsResponse;
|
||||
import org.signal.chat.subscriptions.GetSubscriptionInformationRequest;
|
||||
import org.signal.chat.subscriptions.GetSubscriptionInformationResponse;
|
||||
import org.signal.chat.subscriptions.PaymentMethod;
|
||||
import org.signal.chat.subscriptions.SetDefaultPaymentMethodRequest;
|
||||
import org.signal.chat.subscriptions.SetDefaultPaymentMethodResponse;
|
||||
import org.signal.chat.subscriptions.SetIapSubscriptionRequest;
|
||||
import org.signal.chat.subscriptions.SetIapSubscriptionResponse;
|
||||
import org.signal.chat.subscriptions.SetSubscriptionLevelRequest;
|
||||
import org.signal.chat.subscriptions.SetSubscriptionLevelResponse;
|
||||
import org.signal.chat.subscriptions.SubscriptionsGrpc;
|
||||
import org.signal.chat.subscriptions.UpdateSubscriberRequest;
|
||||
import org.signal.chat.subscriptions.UpdateSubscriberResponse;
|
||||
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.PaymentMethod;
|
||||
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.SubscriptionsGrpc;
|
||||
import org.signal.chat.purchase.UpdateSubscriberRequest;
|
||||
import org.signal.chat.purchase.UpdateSubscriberResponse;
|
||||
import org.signal.libsignal.zkgroup.ServerSecretParams;
|
||||
import org.signal.libsignal.zkgroup.VerificationFailedException;
|
||||
import org.signal.libsignal.zkgroup.donation.DonationPermit;
|
||||
@@ -66,17 +64,10 @@ import org.signal.libsignal.zkgroup.donation.DonationPermitRequest;
|
||||
import org.signal.libsignal.zkgroup.donation.DonationPermitRequestContext;
|
||||
import org.signal.libsignal.zkgroup.donation.DonationPermitResponse;
|
||||
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialResponse;
|
||||
import org.whispersystems.textsecuregcm.badges.BadgeTranslator;
|
||||
import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.SubscriptionConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicBackupConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.entities.Badge;
|
||||
import org.whispersystems.textsecuregcm.entities.BadgeSvg;
|
||||
import org.whispersystems.textsecuregcm.storage.DonationPermits;
|
||||
import org.whispersystems.textsecuregcm.storage.DonationPermitsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.storage.SubscriptionManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Subscriptions;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.AppleAppStoreManager;
|
||||
@@ -118,9 +109,6 @@ public class SubscriptionsGrpcServiceTest extends
|
||||
private final SubscriptionConfiguration subscriptionConfiguration =
|
||||
SubscriptionConfigTestHelper.getSubscriptionConfig();
|
||||
|
||||
private final OneTimeDonationConfiguration oneTimeDonationConfiguration =
|
||||
SubscriptionConfigTestHelper.getOneTimeConfig();
|
||||
|
||||
@Mock
|
||||
private DonationPermits donationPermits;
|
||||
|
||||
@@ -142,15 +130,9 @@ public class SubscriptionsGrpcServiceTest extends
|
||||
@Mock
|
||||
private AppleAppStoreManager appleAppStoreManager;
|
||||
|
||||
@Mock
|
||||
private BadgeTranslator badgeTranslator;
|
||||
|
||||
@Mock
|
||||
private BankMandateTranslator bankMandateTranslator;
|
||||
|
||||
@Mock
|
||||
private DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
|
||||
|
||||
private static final ByteString SUBSCRIBER_ID = ByteString.copyFrom(TestRandomUtil.nextBytes(32));
|
||||
private static final long LEVEL = 5L;
|
||||
private static final String CURRENCY = "usd";
|
||||
@@ -167,9 +149,8 @@ public class SubscriptionsGrpcServiceTest extends
|
||||
when(donationPermits.spend(any(byte[].class), any(Instant.class)))
|
||||
.thenAnswer(answer -> spent.add(new String(answer.getArgument(0, byte[].class))));
|
||||
|
||||
return new SubscriptionsGrpcService(clock, subscriptionConfiguration, oneTimeDonationConfiguration,
|
||||
subscriptionManager, donationPermitsManager, stripeManager, braintreeManager, googlePlayBillingManager,
|
||||
appleAppStoreManager, badgeTranslator, bankMandateTranslator, dynamicConfigurationManager);
|
||||
return new SubscriptionsGrpcService(clock, subscriptionConfiguration, subscriptionManager, donationPermitsManager,
|
||||
stripeManager, braintreeManager, googlePlayBillingManager, appleAppStoreManager, bankMandateTranslator);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -267,7 +248,7 @@ public class SubscriptionsGrpcServiceTest extends
|
||||
final CreatePaymentMethodResponse response = unauthenticatedServiceStub().createPaymentMethod(builder.build());
|
||||
assertEquals(CreatePaymentMethodResponse.ResponseCase.RESULT, response.getResponseCase());
|
||||
// Currently, only stripe is chosen as the payment provider for all supported payment methods
|
||||
assertEquals(org.signal.chat.subscriptions.PaymentProvider.PAYMENT_PROVIDER_STRIPE,
|
||||
assertEquals(org.signal.chat.purchase.PaymentProvider.PAYMENT_PROVIDER_STRIPE,
|
||||
response.getResult().getPaymentProvider());
|
||||
assertEquals("test-client-secret", response.getResult().getClientSecret());
|
||||
}
|
||||
@@ -330,7 +311,7 @@ public class SubscriptionsGrpcServiceTest extends
|
||||
final BraintreeManager.PayPalBillingAgreementApprovalDetails details =
|
||||
new BraintreeManager.PayPalBillingAgreementApprovalDetails("https://fake-approval", "test-billing-token");
|
||||
when(subscriptionManager.addPaymentMethodToCustomer(any(), any(), any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(details));
|
||||
.thenReturn(details);
|
||||
final CreatePayPalPaymentMethodResponse response = unauthenticatedServiceStub().createPayPalPaymentMethod(
|
||||
CreatePayPalPaymentMethodRequest.newBuilder()
|
||||
.setSubscriberId(SUBSCRIBER_ID)
|
||||
@@ -360,7 +341,7 @@ public class SubscriptionsGrpcServiceTest extends
|
||||
@ParameterizedTest
|
||||
@EnumSource(value = SetDefaultPaymentMethodRequest.RequestCase.class, names = {"STRIPE", "BRAINTREE", "SEPA"})
|
||||
void setDefaultPaymentMethod(final SetDefaultPaymentMethodRequest.RequestCase requestCase)
|
||||
throws SubscriptionNotFoundException, SubscriptionForbiddenException {
|
||||
throws SubscriptionNotFoundException, SubscriptionForbiddenException, IOException, SubscriptionProcessorConflictException {
|
||||
final PaymentProvider provider = requestCase == SetDefaultPaymentMethodRequest.RequestCase.BRAINTREE
|
||||
? PaymentProvider.BRAINTREE : PaymentProvider.STRIPE;
|
||||
final Subscriptions.Record record = mock(Subscriptions.Record.class);
|
||||
@@ -368,7 +349,7 @@ public class SubscriptionsGrpcServiceTest extends
|
||||
when(subscriptionManager.getSubscriber(any())).thenReturn(record);
|
||||
if (requestCase == SetDefaultPaymentMethodRequest.RequestCase.SEPA) {
|
||||
when(stripeManager.getGeneratedSepaIdFromSetupIntent(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture("sepa-id"));
|
||||
.thenReturn("sepa-id");
|
||||
}
|
||||
final SetDefaultPaymentMethodRequest.Builder builder = SetDefaultPaymentMethodRequest.newBuilder()
|
||||
.setSubscriberId(SUBSCRIBER_ID);
|
||||
@@ -540,7 +521,7 @@ public class SubscriptionsGrpcServiceTest extends
|
||||
.setLevel(LEVEL).setCurrency(CURRENCY).setIdempotencyKey("test-idempotency-key")
|
||||
.build());
|
||||
assertEquals(SetSubscriptionLevelResponse.ResponseCase.CHARGE_FAILURE, response.getResponseCase());
|
||||
assertEquals(org.signal.chat.subscriptions.PaymentProvider.PAYMENT_PROVIDER_STRIPE,
|
||||
assertEquals(org.signal.chat.purchase.PaymentProvider.PAYMENT_PROVIDER_STRIPE,
|
||||
response.getChargeFailure().getProcessor());
|
||||
assertEquals("card_declined", response.getChargeFailure().getCode());
|
||||
assertEquals("Insufficient funds", response.getChargeFailure().getMessage());
|
||||
@@ -573,7 +554,7 @@ public class SubscriptionsGrpcServiceTest extends
|
||||
assertEquals(1000L, response.getSuccess().getEndOfCurrentPeriod());
|
||||
assertTrue(response.getSuccess().getActive());
|
||||
assertFalse(response.getSuccess().getCancelAtPeriodEnd());
|
||||
assertEquals(org.signal.chat.subscriptions.PaymentProvider.PAYMENT_PROVIDER_STRIPE,
|
||||
assertEquals(org.signal.chat.purchase.PaymentProvider.PAYMENT_PROVIDER_STRIPE,
|
||||
response.getSuccess().getProcessor());
|
||||
assertEquals(PaymentMethod.PAYMENT_METHOD_CARD, response.getSuccess().getPaymentMethod());
|
||||
}
|
||||
@@ -640,7 +621,7 @@ public class SubscriptionsGrpcServiceTest extends
|
||||
.setReceiptCredentialRequest(ByteString.copyFrom(TestRandomUtil.nextBytes(97)))
|
||||
.build());
|
||||
assertEquals(GetReceiptCredentialsResponse.ResponseCase.PAYMENT_REQUIRED, response.getResponseCase());
|
||||
assertEquals(org.signal.chat.subscriptions.PaymentProvider.PAYMENT_PROVIDER_STRIPE,
|
||||
assertEquals(org.signal.chat.purchase.PaymentProvider.PAYMENT_PROVIDER_STRIPE,
|
||||
response.getPaymentRequired().getChargeFailure().getProcessor());
|
||||
assertEquals("card_declined", response.getPaymentRequired().getChargeFailure().getCode());
|
||||
}
|
||||
@@ -703,104 +684,12 @@ public class SubscriptionsGrpcServiceTest extends
|
||||
assertEquals(expectedCase, response.getResponseCase());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getConfiguration() {
|
||||
final DynamicConfiguration dynamicConfiguration = mock(DynamicConfiguration.class);
|
||||
when(dynamicConfigurationManager.getConfiguration()).thenReturn(dynamicConfiguration);
|
||||
when(dynamicConfiguration.getBackupConfiguration())
|
||||
.thenReturn(new DynamicBackupConfiguration(null, null, null, null, 1234L));
|
||||
|
||||
when(stripeManager.supportsPaymentMethod(any())).thenCallRealMethod();
|
||||
when(stripeManager.getSupportedCurrenciesForPaymentMethod(
|
||||
org.whispersystems.textsecuregcm.subscriptions.PaymentMethod.CARD))
|
||||
.thenReturn(Set.of("usd", "jpy", "bif", "eur"));
|
||||
when(stripeManager.getSupportedCurrenciesForPaymentMethod(
|
||||
org.whispersystems.textsecuregcm.subscriptions.PaymentMethod.SEPA_DEBIT))
|
||||
.thenReturn(Set.of("eur"));
|
||||
when(stripeManager.getSupportedCurrenciesForPaymentMethod(
|
||||
org.whispersystems.textsecuregcm.subscriptions.PaymentMethod.IDEAL))
|
||||
.thenReturn(Set.of("eur"));
|
||||
when(braintreeManager.supportsPaymentMethod(any())).thenCallRealMethod();
|
||||
when(braintreeManager.getSupportedCurrenciesForPaymentMethod(
|
||||
org.whispersystems.textsecuregcm.subscriptions.PaymentMethod.PAYPAL))
|
||||
.thenReturn(Set.of("usd", "jpy"));
|
||||
|
||||
when(badgeTranslator.translate(any(), eq("B1"))).thenReturn(new Badge("B1", "cat1", "name1", "desc1",
|
||||
List.of("l", "m", "h", "x", "xx", "xxx"), "SVG", List.of(new BadgeSvg("sl", "sd"))));
|
||||
when(badgeTranslator.translate(any(), eq("B2"))).thenReturn(new Badge("B2", "cat2", "name2", "desc2",
|
||||
List.of("l", "m", "h", "x", "xx", "xxx"), "SVG", List.of(new BadgeSvg("sl", "sd"))));
|
||||
when(badgeTranslator.translate(any(), eq("B3"))).thenReturn(new Badge("B3", "cat3", "name3", "desc3",
|
||||
List.of("l", "m", "h", "x", "xx", "xxx"), "SVG", List.of(new BadgeSvg("sl", "sd"))));
|
||||
when(badgeTranslator.translate(any(), eq("BOOST"))).thenReturn(new Badge("BOOST", "boost1", "boost1", "boost1",
|
||||
List.of("l", "m", "h", "x", "xx", "xxx"), "SVG", List.of(new BadgeSvg("sl", "sd"))));
|
||||
when(badgeTranslator.translate(any(), eq("GIFT"))).thenReturn(new Badge("GIFT", "gift1", "gift1", "gift1",
|
||||
List.of("l", "m", "h", "x", "xx", "xxx"), "SVG", List.of(new BadgeSvg("sl", "sd"))));
|
||||
|
||||
final GetConfigurationResponse response = unauthenticatedServiceStub()
|
||||
.getConfiguration(GetConfigurationRequest.newBuilder().build());
|
||||
|
||||
assertEquals("10000", response.getSepaMaximumEuros());
|
||||
|
||||
assertEquals(30L, response.getBackup().getFreeTierMediaDays());
|
||||
final GetConfigurationResponse.BackupLevelConfiguration backupLevel =
|
||||
response.getBackup().getLevelsOrThrow(201L);
|
||||
assertEquals(1234L, backupLevel.getStorageAllowanceBytes());
|
||||
assertEquals("testPlayProductId", backupLevel.getPlayProductId());
|
||||
assertEquals(40L, backupLevel.getMediaTtlDays());
|
||||
|
||||
final GetConfigurationResponse.CurrencyConfiguration usd = response.getCurrenciesOrThrow("usd");
|
||||
assertEquals("2.50", usd.getMinimum());
|
||||
assertEquals(List.of(PaymentMethod.PAYMENT_METHOD_CARD, PaymentMethod.PAYMENT_METHOD_PAYPAL),
|
||||
usd.getSupportedPaymentMethodsList());
|
||||
assertEquals(List.of("5.50", "6", "7", "8", "9", "10"), usd.getOneTimeOrThrow(1L).getAmountsList());
|
||||
assertEquals(List.of("20"), usd.getOneTimeOrThrow(100L).getAmountsList());
|
||||
assertEquals(Map.of(5L, "5", 15L, "15", 35L, "35"), usd.getSubscriptionMap());
|
||||
assertEquals(Map.of(201L, "5"), usd.getBackupSubscriptionMap());
|
||||
|
||||
final GetConfigurationResponse.CurrencyConfiguration jpy = response.getCurrenciesOrThrow("jpy");
|
||||
assertEquals("250", jpy.getMinimum());
|
||||
assertEquals(List.of(PaymentMethod.PAYMENT_METHOD_CARD, PaymentMethod.PAYMENT_METHOD_PAYPAL),
|
||||
jpy.getSupportedPaymentMethodsList());
|
||||
assertEquals(List.of("550", "600", "700", "800", "900", "1000"), jpy.getOneTimeOrThrow(1L).getAmountsList());
|
||||
assertEquals(List.of("2000"), jpy.getOneTimeOrThrow(100L).getAmountsList());
|
||||
assertEquals(Map.of(5L, "500", 15L, "1500", 35L, "3500"), jpy.getSubscriptionMap());
|
||||
assertEquals(Map.of(201L, "500"), jpy.getBackupSubscriptionMap());
|
||||
|
||||
final GetConfigurationResponse.CurrencyConfiguration bif = response.getCurrenciesOrThrow("bif");
|
||||
assertEquals("2500", bif.getMinimum());
|
||||
assertEquals(List.of(PaymentMethod.PAYMENT_METHOD_CARD), bif.getSupportedPaymentMethodsList());
|
||||
assertEquals(List.of("5500", "6000", "7000", "8000", "9000", "10000"), bif.getOneTimeOrThrow(1L).getAmountsList());
|
||||
assertEquals(List.of("20000"), bif.getOneTimeOrThrow(100L).getAmountsList());
|
||||
assertEquals(Map.of(5L, "5000", 15L, "15000", 35L, "35000"), bif.getSubscriptionMap());
|
||||
assertEquals(Map.of(201L, "5000"), bif.getBackupSubscriptionMap());
|
||||
|
||||
final GetConfigurationResponse.CurrencyConfiguration eur = response.getCurrenciesOrThrow("eur");
|
||||
assertEquals("3", eur.getMinimum());
|
||||
assertEquals(
|
||||
List.of(PaymentMethod.PAYMENT_METHOD_CARD, PaymentMethod.PAYMENT_METHOD_SEPA_DEBIT,
|
||||
PaymentMethod.PAYMENT_METHOD_IDEAL),
|
||||
eur.getSupportedPaymentMethodsList());
|
||||
assertEquals(List.of("5", "10", "20", "30", "50", "100"), eur.getOneTimeOrThrow(1L).getAmountsList());
|
||||
assertEquals(List.of("5"), eur.getOneTimeOrThrow(100L).getAmountsList());
|
||||
assertEquals(Map.of(5L, "5", 15L, "15", 35L, "35"), eur.getSubscriptionMap());
|
||||
assertEquals(Map.of(201L, "5"), eur.getBackupSubscriptionMap());
|
||||
|
||||
assertEquals("B1", response.getLevelsOrThrow(5L).getBadge().getBadge().getId());
|
||||
assertEquals(0L, response.getLevelsOrThrow(5L).getBadge().getDurationSeconds());
|
||||
assertEquals("B2", response.getLevelsOrThrow(15L).getBadge().getBadge().getId());
|
||||
assertEquals("B3", response.getLevelsOrThrow(35L).getBadge().getBadge().getId());
|
||||
assertEquals("BOOST", response.getLevelsOrThrow(1L).getBadge().getBadge().getId());
|
||||
assertTrue(response.getLevelsOrThrow(1L).getBadge().getDurationSeconds() > 0);
|
||||
assertEquals("GIFT", response.getLevelsOrThrow(100L).getBadge().getBadge().getId());
|
||||
assertTrue(response.getLevelsOrThrow(100L).getBadge().getDurationSeconds() > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getBankMandate() {
|
||||
when(bankMandateTranslator.translate(any(), eq(BankTransferType.SEPA_DEBIT))).thenReturn("test-mandate");
|
||||
final GetBankMandateResponse response = unauthenticatedServiceStub().getBankMandate(
|
||||
GetBankMandateRequest.newBuilder()
|
||||
.setBankTransferType(org.signal.chat.subscriptions.BankTransferType.BANK_TRANSFER_TYPE_SEPA_DEBIT)
|
||||
.setBankTransferType(org.signal.chat.purchase.BankTransferType.BANK_TRANSFER_TYPE_SEPA_DEBIT)
|
||||
.build());
|
||||
assertEquals("test-mandate", response.getMandate());
|
||||
}
|
||||
|
||||
+71
@@ -2,10 +2,12 @@ package org.whispersystems.textsecuregcm.storage.foundationdb;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyBoolean;
|
||||
import static org.mockito.ArgumentMatchers.anyInt;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@@ -28,6 +30,7 @@ import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
@@ -417,6 +420,74 @@ class FoundationDbMessagePublisherTest {
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void onRequestFlowControl() {
|
||||
final MessageProtos.Envelope message1 = FoundationDbMessageStoreTest.generateRandomMessage(false);
|
||||
final MessageProtos.Envelope message2 = FoundationDbMessageStoreTest.generateRandomMessage(false);
|
||||
final MessageProtos.Envelope message3 = FoundationDbMessageStoreTest.generateRandomMessage(false);
|
||||
|
||||
final KeyValue keyValue1 = mockKeyValue((byte) 5, message1);
|
||||
final KeyValue keyValue2 = mockKeyValue((byte) 6, message2);
|
||||
final KeyValue keyValue3 = mockKeyValue((byte) 7, message3);
|
||||
|
||||
final AsyncIterable<KeyValue> batch1 = mock(AsyncIterable.class);
|
||||
when(batch1.asList()).thenReturn(CompletableFuture.completedFuture(List.of(keyValue1, keyValue2)));
|
||||
|
||||
final AsyncIterable<KeyValue> batch2 = mock(AsyncIterable.class);
|
||||
when(batch2.asList()).thenReturn(CompletableFuture.completedFuture(List.of(keyValue3)));
|
||||
|
||||
final Transaction transaction = mock(Transaction.class);
|
||||
when(transaction.getRange(any(KeySelector.class), any(KeySelector.class), anyInt(), anyBoolean(), any(
|
||||
StreamingMode.class)))
|
||||
.thenReturn(batch1)
|
||||
.thenReturn(batch2);
|
||||
|
||||
when(database.runAsync(any(Function.class))).thenAnswer(
|
||||
(Answer<CompletableFuture<List<? extends MessageStreamEntry>>>) invocationOnMock -> {
|
||||
final Function<Transaction, CompletableFuture<List<? extends MessageStreamEntry>>> f = invocationOnMock.getArgument(
|
||||
0);
|
||||
return f.apply(transaction);
|
||||
});
|
||||
|
||||
final CountDownLatch latch = new CountDownLatch(1);
|
||||
final FoundationDbMessagePublisher finitePublisher = new FoundationDbMessagePublisher(
|
||||
database,
|
||||
CLOCK,
|
||||
KeySelector.firstGreaterOrEqual(SUBSPACE_RANGE.begin),
|
||||
KeySelector.firstGreaterOrEqual(SUBSPACE_RANGE.end),
|
||||
2,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
(oldState, newState) -> {
|
||||
if (oldState == FoundationDbMessagePublisher.State.FETCHING_MESSAGES
|
||||
&& newState == FoundationDbMessagePublisher.State.MESSAGES_AVAILABLE) {
|
||||
latch.countDown();
|
||||
}
|
||||
},
|
||||
NOOP_ON_PAGE_FETCH
|
||||
);
|
||||
|
||||
// Request two messages one at a time and verify that we only fetch a single batch (batch size = 2) and not two batches
|
||||
StepVerifier.create(finitePublisher.getMessages(), 1)
|
||||
.expectNext(getExpectedMessageStreamEntry(keyValue1))
|
||||
.then(() -> {
|
||||
// Wait for the whole batch to have completed publishing before requesting the next message
|
||||
try {
|
||||
assertTrue(latch.await(500, TimeUnit.MILLISECONDS));
|
||||
} catch (final InterruptedException e) {
|
||||
fail(e);
|
||||
}
|
||||
})
|
||||
.thenRequest(1)
|
||||
.expectNext(getExpectedMessageStreamEntry(keyValue2))
|
||||
.verifyTimeout(Duration.ofMillis(500));
|
||||
|
||||
verify(transaction, times(1)).getRange(any(KeySelector.class), any(KeySelector.class), anyInt(), anyBoolean(),
|
||||
any());
|
||||
|
||||
}
|
||||
|
||||
private FoundationDbMessageStreamEntry.Message getExpectedMessageStreamEntry(final KeyValue keyValue) {
|
||||
try {
|
||||
return new FoundationDbMessageStreamEntry.Message(FoundationDbMessageStore.getVersionstamp(keyValue.getKey()),
|
||||
|
||||
+20
-47
@@ -8,26 +8,26 @@ package org.whispersystems.textsecuregcm.subscriptions;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.lenient;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.braintree.graphql.clientoperation.CreatePayPalOneTimePaymentMutation;
|
||||
import jakarta.ws.rs.ServiceUnavailableException;
|
||||
import java.io.IOException;
|
||||
import java.math.BigDecimal;
|
||||
import java.net.http.HttpHeaders;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.time.Duration;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.whispersystems.textsecuregcm.http.FaultTolerantHttpClient;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class BraintreeGraphqlClientTest {
|
||||
|
||||
private static final String CURRENCY = "xts";
|
||||
@@ -36,49 +36,40 @@ class BraintreeGraphqlClientTest {
|
||||
private static final String LOCALE = "xx";
|
||||
private static final String LOCALIZED_LINE_ITEM_NAME = "Donation to Signal Technology Foundation";
|
||||
|
||||
@Mock
|
||||
private FaultTolerantHttpClient httpClient;
|
||||
|
||||
@Mock
|
||||
private HttpResponse<Object> response;
|
||||
|
||||
private BraintreeGraphqlClient braintreeGraphqlClient;
|
||||
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
httpClient = mock(FaultTolerantHttpClient.class);
|
||||
void setUp() throws IOException {
|
||||
lenient().when(httpClient.send(any(), any())).thenReturn(response);
|
||||
|
||||
braintreeGraphqlClient = new BraintreeGraphqlClient(httpClient, "https://example.com", "public", "super-secret");
|
||||
}
|
||||
|
||||
@Test
|
||||
void createPayPalOneTimePayment() {
|
||||
|
||||
final HttpResponse<Object> response = mock(HttpResponse.class);
|
||||
when(httpClient.sendAsync(any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(response));
|
||||
|
||||
void createPayPalOneTimePayment() throws IOException {
|
||||
final String paymentId = "PAYID-AAA1AAAA1A11111AA111111A";
|
||||
when(response.body())
|
||||
.thenReturn(createPayPalOneTimePaymentResponse(paymentId));
|
||||
when(response.statusCode())
|
||||
.thenReturn(200);
|
||||
|
||||
final CompletableFuture<CreatePayPalOneTimePaymentMutation.CreatePayPalOneTimePayment> future = braintreeGraphqlClient.createPayPalOneTimePayment(
|
||||
final CreatePayPalOneTimePaymentMutation.CreatePayPalOneTimePayment result = braintreeGraphqlClient.createPayPalOneTimePayment(
|
||||
BigDecimal.ONE, CURRENCY,
|
||||
RETURN_URL, CANCEL_URL, LOCALE, LOCALIZED_LINE_ITEM_NAME);
|
||||
|
||||
assertTimeoutPreemptively(Duration.ofSeconds(3), () -> {
|
||||
final CreatePayPalOneTimePaymentMutation.CreatePayPalOneTimePayment result = future.get();
|
||||
|
||||
assertEquals(paymentId, result.paymentId);
|
||||
assertNotNull(result.approvalUrl);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void createPayPalOneTimePaymentHttpError() {
|
||||
|
||||
final HttpResponse<Object> response = mock(HttpResponse.class);
|
||||
when(httpClient.sendAsync(any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(response));
|
||||
|
||||
void createPayPalOneTimePaymentHttpError() throws IOException {
|
||||
when(response.statusCode())
|
||||
.thenReturn(500);
|
||||
final HttpHeaders httpheaders = mock(HttpHeaders.class);
|
||||
@@ -86,39 +77,21 @@ class BraintreeGraphqlClientTest {
|
||||
when(response.headers())
|
||||
.thenReturn(httpheaders);
|
||||
|
||||
final CompletableFuture<CreatePayPalOneTimePaymentMutation.CreatePayPalOneTimePayment> future = braintreeGraphqlClient.createPayPalOneTimePayment(
|
||||
assertThrows(IOException.class, () -> braintreeGraphqlClient.createPayPalOneTimePayment(
|
||||
BigDecimal.ONE, CURRENCY,
|
||||
RETURN_URL, CANCEL_URL, LOCALE, LOCALIZED_LINE_ITEM_NAME);
|
||||
|
||||
assertTimeoutPreemptively(Duration.ofSeconds(3), () -> {
|
||||
|
||||
final ExecutionException e = assertThrows(ExecutionException.class, future::get);
|
||||
|
||||
assertTrue(e.getCause() instanceof ServiceUnavailableException);
|
||||
});
|
||||
RETURN_URL, CANCEL_URL, LOCALE, LOCALIZED_LINE_ITEM_NAME));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createPayPalOneTimePaymentGraphQlError() {
|
||||
|
||||
final HttpResponse<Object> response = mock(HttpResponse.class);
|
||||
when(httpClient.sendAsync(any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(response));
|
||||
|
||||
when(response.body())
|
||||
.thenReturn(createErrorResponse("createPayPalOneTimePayment", "12345"));
|
||||
when(response.statusCode())
|
||||
.thenReturn(200);
|
||||
|
||||
final CompletableFuture<CreatePayPalOneTimePaymentMutation.CreatePayPalOneTimePayment> future = braintreeGraphqlClient.createPayPalOneTimePayment(
|
||||
assertThrows(IOException.class, () -> braintreeGraphqlClient.createPayPalOneTimePayment(
|
||||
BigDecimal.ONE, CURRENCY,
|
||||
RETURN_URL, CANCEL_URL, LOCALE, LOCALIZED_LINE_ITEM_NAME);
|
||||
|
||||
assertTimeoutPreemptively(Duration.ofSeconds(3), () -> {
|
||||
|
||||
final ExecutionException e = assertThrows(ExecutionException.class, future::get);
|
||||
assertTrue(e.getCause() instanceof ServiceUnavailableException);
|
||||
});
|
||||
RETURN_URL, CANCEL_URL, LOCALE, LOCALIZED_LINE_ITEM_NAME));
|
||||
}
|
||||
|
||||
private String createPayPalOneTimePaymentResponse(final String paymentId) {
|
||||
|
||||
@@ -155,10 +155,8 @@ storageService.userAuthenticationTokenSharedSecret: AAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
||||
|
||||
# The below secrets were generated exclusively for testing purposes. Do not use them in any other context.
|
||||
zkConfig-libsignal-0.42.serverSecret: ALxy0qUiV9B3OgF1GzTgn6g4NSN22ww87p5xOlYkypQJIqxoTBGOPREr4ZXvOfQ/tFYQJxn3xoFJ5DKt+mDOJw8KzWephNaaXBSLcbWb/fPfSUjoXnPL+fcU26OpMIUrIVews/i0Eh4ongRWuLfFUpLyZ34wfgpKkWbIUBjbVT4M5e7GzRPVFOBGibICk9Q66o9l3K4PphKaoMQKlGPo4g85xsVH1HFN5J5u4/pdq80+3E7WvWN4c8NpDZQ7RqtECDpawSc/J4vim9tL7QR6hFYwzvA0cmCcM0NCPFpp69EHB1eRksDvPHiA+NuMqoFwXwIzSHzA86ALPxnyLKB7KgBG06DxfMmMav3dij6giTawgATRsoNFLQ/ol6H0TtYJCAp8oB0D4EV2q7hSue3Kxzh1Vc88/nmLuRR9G3EefC0+CMcxJFQwDMgjFvFBKx3o6m9gJLevYiKcm/NxXX9WtnEzqAh2DRr0G0fvk9NZF2Lw2kWgAX2qkPHZLJ3nKA90BgryBAJsk8Q78N5ghBhQzdgikURLC+mX1fbmMzkmGcwCYDnLpo8qjrIoBZzDAjI4Ty04MaJcLowJqNMmK29btza50WiZdsd4tuVqQAKlqJcERCsUewlZSkWpsDLrZkeUBY0rGCi51FW5WOUvdXwTHtTL2hlcBqP/E8cbBC+yce8AurjJ6Z9HVtM7tVk7a5xRAqwoFRSH7eq5BA60hDq2sgWIQaN1owunKZvsHFn0qzoGKuWAEO0PpbGbHtFDUjxzBkgUIN13yIbem9KPeZm9ZVrjkyDo3uZZsfFFUHnFeasKOt9WMJLLx1s7DttJ4Ns2o02q4e+aQ60oMeWsyMuzKgNMDHgDgfqHxbCi2rm20SgoHnuoph6XArmEOX6a1xLJVxgDtgfm1IbcyyqROXYxe9v2RvMUAnjbLI/fm0rXXhldjVX7Yoo7ZGAlVBuGOC28haRrd684Lcajdequ6Css1geOzOVVH/BGnJtf3RFSMXIv/YByG21/cgL9KFYqQHqZZeLNQpweILMnU0/iVK/fjLvrhyI2jNy1B0Ox62zE2o8EdVT/H1WgXa2NHC591aEqI5EXwribRKUM56v/O3IDBAxC5CLIQcUeDhWouaFqXjfxNza9rFC69smtUXl3sx8KG6Ze7VkXb372daAN+rMWIdq5kbRcetkXxuqTuYOz4NsDnEPnBNNO6hqOv6+dZAQK3wmhOah3NIL0kKNUHpuk+gidQkLehBvahNKpUfh9yBMkEcLNkR7D1r8fAcrA7u2sCKfRero8FOkCc9ChawShJXdcGtKv50d2/4vJp9B0ddUBYdFnbM/siX4VJghb+rSkhCkkXXS7QXFfbO5A4WJLkwthkNezNgqCBmEoda7UcOOaW9KQMFisRy74OZagCUAJCPC4UJw1/N4IJD7Dtw2cNtaxwFyuG6i7sdm9u3Xr9h0JcvKn5Z3BLxmR6WkhO/IraGw+9/ijFpEtB9VFhdQxfnnj4JRneZtQxC9nAY0liDuO41OhGYaWinVVRkljKe7GAmw726P1wYiyd2ajlkbI/7KB9VwxEicEijeyuR6UZDUFqOPk4q+fdkBRS2GuGKiy4ISgha6sVRkb5sLlAsRhmG1W0Anh8d2dHxmE8CzyoAXbschIeY2LJTUIORpvAaFrDI74dagBDNlIVnHw89PGYWnosia9YFMLpsYyjOccQKAGKJLZ8MdcgRw8W2Mw2AwZbQWUUU1VZxdWX6y878WJ6g4at5NJ2YpdZ/qh5zBTDbTDpGnTsv9Ioyw5+91h6qagDXecb1wekN0RZsI3KWXQeOZZ+uxTNRqqpWZhH9QtrEsPRdNyOlVJDmJ1H2Rl3o30Crt8j6EM6ZgR444GuDf/jATe9shz3Ljc0S5/OTEAJL54OfHq9jGgtXS+05AuhlxCC9zYpEBb30xnZD6zxXnz6IB//uVROuWc1BEFhkvn+JcJxpapbKH6PthuOzMVRkf+I3Xz3/bNjiQSlQkmAXlgB1YujgABYnJ6yJXQKP2mR4UJ3UYoGroYoafWycDa+vUYYqIMcK6tbIgvxFx8TmMoQ1MueOIzDt0Nyx3Uov5qVvcG8gyflIv4fbzlu7GTYE8Ov6sRGY8KzF5ywxvrq0VldgfoGF4AGdQ3RxB5EDdlHIvlOG8VRoD+7Ch/S1kemdyvD2co9wN/GfU58Q1DO7dSQTl/O86t1eZBp+8H4IIarAgLunN/vkV34LAYjk1DOfeNxrCnfHz9RWtT3Vy3FJKuaQUotgZRyu36BLSs/ozriMR1nkT2+Luknw/zDD496ZvyAwvtG18Tk5B5b3DSMSUq9vA4h8KKCFfkgTHNeOHFyogNkfwaeGEflkrckI4RTtGrIL+lmW+1LYRoDU8F2T4VzAnyqsfmfT5+g6nbzw7FRXGfEu/E94Xaacj0t90t+eqtBruaoJ9kqw4iJmQdrSonz4fo4yOAXukaTnzFnalXZdoFjNpSbMWOwFhalgT4fI8mUnZBoVOulWrFfs1exJuDy3fki99Z9kwT1gFnZ4SsO6fCRoTiINCEeXkhcCFscOuvZP9su7zhyXWhobzNsct/ejd+CHyDKoNPBjNId5hGwnIAP5F55x+n51UIPvCkotwIGsvbfExLMw/JgwCJCDSHNgZEmXO+xEVozKRbUDK8d0mR46M59k8qaPKkKAORatQPVXOyszQTLx8gnPf/HDDqthyyp7mfjfE09vv3CpREfzkGYZpMWv1aDG2AHpAdrOH3cVW2UQq9uPRtkiHZMZg9CQnapTCmq3YAvsKugvU2CnrnJlACFYO1Hr5RpjfIRMCkBrfHrdFQEwB4/u6opMApJThcbXzhbVEwIwOq/ZcleloJKnN4GdaZyLFphtApVSuMVYDNm0X6KNGSl1kFbgxs8gBBhLxXqqhdfoBnwOtOXHO+kFGY1WzGUJZviHD43glxBIWPRSjD0pPvuWX91IWv/GZuCIkwCa34p+P9v7iKRuoBGievGCJJ+5SUoBQyhhQdpG+gbw1Bs3KSPwkx0IulpQqkInUCyVgxRXZWI61AkDNr7ybYMhq0nPPY3V0xYzN9Wltf8c37m3IWVkzGR3a0JjoUUWtFaCY9fasiOQM1nZUMe/0UTV2ZKjD4US9c2PEHrPPlwVowar4PlUJU1KIAjgsCyo9DhZPyEgPjGYu+tGpMcUImLukfebXsgzFFhyLgLktlMwFHNn6JHchCURY58OOcMzDKK/6IuLU621a+d8gP8U22MozRrL+GNEYwiyF9XM4Hp+ovB3yv6VFkBp7ukAJDETnNy+nPPjt0ShUpp4hj+WDWo/fs6Oy/fs0wPdziBPrWQ7Dn0vDGsXVbTib8rd4UucpZdGaY1yktsG4MNHAMVv+IH1hYcg87bfsUJbfuHgvLB1l5Qz8j7/Ezi54RFQBGS3QkDQnCl/mMmrNCe5xe1soC+rsCRblHuJjujjK/CxgYEs2Lc9ZWPc3FyzGQbblH5hUX1MxP0V1DM/VxpI8EGVWTk6Q3W1yX16EiWkauVbHsyScbniotURYRstCUmA1Qnz9bsSBgjuCftVHZZ4lFmWogd976tG5uGQ+tvu6xCqH+EsGOQ843I/5w0xTPTJcFyQ9cuRoTPzFIeP2wa9AA
|
||||
genericZkConfig.serverSecret: AIZmPk8ms6TWBTGFcFE1iEuu4kSpTRL1EAPA2ZVWm4EIIF/N811ZhILbCx8QSLBf90mNXhUtsfNF5PY5UdnJMgBGu3AtrVs5erRXf5hi6RxvCkl1QnYs/tcuUGNbkejyR9bPR2uJaK6CxGJS0RRUDWf8f2hQloe/+kWKilM1I/MHSV2+PcyCDJIigPi9RhbD2STXc6cHEpYXReg+1OYSEQk3K2M0qnUoVOAjbPuFXANEPU+106f37w/iF6MhyfWyDCb+oit29DFtoDS31cxheB3x1KVga2ErfnIyHpQrSWYHUdGPZLXc0xRmaa0VwDyyXzK0o3w4oS/F9+xqWYUWkwgsAm9e7dP4l0qVolnPQ67uNj7BFG4JQ0vXxD/JJQ+5B4bHyK+v5ndJpRMXDC9rJw8ehopvDCTXSoICqN7nvY8Fyqhf5zkM880Su2XiBa2paDTVuZgwq07zBeDrrPc2zQ8A4neV6++t95veOfpp94FymnHJ8ILaznKqzJluGDdtCA==
|
||||
callingZkConfig.serverSecret: AIZmPk8ms6TWBTGFcFE1iEuu4kSpTRL1EAPA2ZVWm4EIIF/N811ZhILbCx8QSLBf90mNXhUtsfNF5PY5UdnJMgBGu3AtrVs5erRXf5hi6RxvCkl1QnYs/tcuUGNbkejyR9bPR2uJaK6CxGJS0RRUDWf8f2hQloe/+kWKilM1I/MHSV2+PcyCDJIigPi9RhbD2STXc6cHEpYXReg+1OYSEQk3K2M0qnUoVOAjbPuFXANEPU+106f37w/iF6MhyfWyDCb+oit29DFtoDS31cxheB3x1KVga2ErfnIyHpQrSWYHUdGPZLXc0xRmaa0VwDyyXzK0o3w4oS/F9+xqWYUWkwgsAm9e7dP4l0qVolnPQ67uNj7BFG4JQ0vXxD/JJQ+5B4bHyK+v5ndJpRMXDC9rJw8ehopvDCTXSoICqN7nvY8Fyqhf5zkM880Su2XiBa2paDTVuZgwq07zBeDrrPc2zQ8A4neV6++t95veOfpp94FymnHJ8ILaznKqzJluGDdtCA==
|
||||
backupsZkConfig.serverSecret: AIZmPk8ms6TWBTGFcFE1iEuu4kSpTRL1EAPA2ZVWm4EIIF/N811ZhILbCx8QSLBf90mNXhUtsfNF5PY5UdnJMgBGu3AtrVs5erRXf5hi6RxvCkl1QnYs/tcuUGNbkejyR9bPR2uJaK6CxGJS0RRUDWf8f2hQloe/+kWKilM1I/MHSV2+PcyCDJIigPi9RhbD2STXc6cHEpYXReg+1OYSEQk3K2M0qnUoVOAjbPuFXANEPU+106f37w/iF6MhyfWyDCb+oit29DFtoDS31cxheB3x1KVga2ErfnIyHpQrSWYHUdGPZLXc0xRmaa0VwDyyXzK0o3w4oS/F9+xqWYUWkwgsAm9e7dP4l0qVolnPQ67uNj7BFG4JQ0vXxD/JJQ+5B4bHyK+v5ndJpRMXDC9rJw8ehopvDCTXSoICqN7nvY8Fyqhf5zkM880Su2XiBa2paDTVuZgwq07zBeDrrPc2zQ8A4neV6++t95veOfpp94FymnHJ8ILaznKqzJluGDdtCA==
|
||||
profileAvatarsZkConfig.serverSecret: AIZmPk8ms6TWBTGFcFE1iEuu4kSpTRL1EAPA2ZVWm4EIIF/N811ZhILbCx8QSLBf90mNXhUtsfNF5PY5UdnJMgBGu3AtrVs5erRXf5hi6RxvCkl1QnYs/tcuUGNbkejyR9bPR2uJaK6CxGJS0RRUDWf8f2hQloe/+kWKilM1I/MHSV2+PcyCDJIigPi9RhbD2STXc6cHEpYXReg+1OYSEQk3K2M0qnUoVOAjbPuFXANEPU+106f37w/iF6MhyfWyDCb+oit29DFtoDS31cxheB3x1KVga2ErfnIyHpQrSWYHUdGPZLXc0xRmaa0VwDyyXzK0o3w4oS/F9+xqWYUWkwgsAm9e7dP4l0qVolnPQ67uNj7BFG4JQ0vXxD/JJQ+5B4bHyK+v5ndJpRMXDC9rJw8ehopvDCTXSoICqN7nvY8Fyqhf5zkM880Su2XiBa2paDTVuZgwq07zBeDrrPc2zQ8A4neV6++t95veOfpp94FymnHJ8ILaznKqzJluGDdtCA==
|
||||
chatZkConfig.serverSecret: AIZmPk8ms6TWBTGFcFE1iEuu4kSpTRL1EAPA2ZVWm4EIIF/N811ZhILbCx8QSLBf90mNXhUtsfNF5PY5UdnJMgBGu3AtrVs5erRXf5hi6RxvCkl1QnYs/tcuUGNbkejyR9bPR2uJaK6CxGJS0RRUDWf8f2hQloe/+kWKilM1I/MHSV2+PcyCDJIigPi9RhbD2STXc6cHEpYXReg+1OYSEQk3K2M0qnUoVOAjbPuFXANEPU+106f37w/iF6MhyfWyDCb+oit29DFtoDS31cxheB3x1KVga2ErfnIyHpQrSWYHUdGPZLXc0xRmaa0VwDyyXzK0o3w4oS/F9+xqWYUWkwgsAm9e7dP4l0qVolnPQ67uNj7BFG4JQ0vXxD/JJQ+5B4bHyK+v5ndJpRMXDC9rJw8ehopvDCTXSoICqN7nvY8Fyqhf5zkM880Su2XiBa2paDTVuZgwq07zBeDrrPc2zQ8A4neV6++t95veOfpp94FymnHJ8ILaznKqzJluGDdtCA==
|
||||
|
||||
paymentsService.userAuthenticationTokenSharedSecret: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= # base64-encoded 32-byte secret shared with MobileCoin services used to generate auth tokens for Signal users
|
||||
paymentsService.fixerApiKey: unset
|
||||
|
||||
@@ -327,18 +327,15 @@ storageService:
|
||||
9Kxq0DY7RCEpdHMCKcOL
|
||||
-----END CERTIFICATE-----
|
||||
|
||||
zkConfig:
|
||||
serverPublic: AAp8oB0D4EV2q7hSue3Kxzh1Vc88/nmLuRR9G3EefC0+CMcxJFQwDMgjFvFBKx3o6m9gJLevYiKcm/NxXX9WtnFMDHgDgfqHxbCi2rm20SgoHnuoph6XArmEOX6a1xLJVxgDtgfm1IbcyyqROXYxe9v2RvMUAnjbLI/fm0rXXhldjszlVR/wRpybX90RUjFyL/2Achttf3IC/ShWKkB6mWXwuFCcNfzeCCQ+w7cNnDbWscBcrhuou7HZvbt16/YdCXLyp+WdwS8ZkelpITvyK2hsPvf4oxaRLQfVRYXUMX55xpapbKH6PthuOzMVRkf+I3Xz3/bNjiQSlQkmAXlgB1YujgABYnJ6yJXQKP2mR4UJ3UYoGroYoafWycDa+vUYYozaUmzFjsBYWpYE+HyPJlJ2QaFTrpVqxX7NXsSbg8t35IvfWfZME9YBZ2eErDunwkaE4iDQhHl5IXAhbHDrr2QaJ68YIkn7lJSgFDKGFB2kb6BvDUGzcpI/CTHQi6WlCqQidQLJWDFFdlYjrUCQM2vvJtgyGrSc89jdXTFjM31aqmtcPWgWL0qv+RmK/BC392Nsu8WoSJcAE4yhccQuRSemtolgwewnjasoOFBNOPh4+pX55SwhyTVgtwl+NTNVNFydxGp9Me8ogRWElzwA9BFtNAgQtlfgIyZRTetFqLkYmIBDxwMcpizDKES5lPhV2uJJuzcMq/06mVQz2OrXgglWk01uN8U59pfNFpTZhcGQv+MHjwEAudq5eLpt3aFrdxJ7D26Fwl5j215SJ0yZo7vmSEML1vf7FaGh0IL57bRpCvdebB5WapSChUX+PPvCXohVjGrERFvQpeET6pydGGlEKYLWuWa3zFGmPvJJYZ/QfcmIP9zyhqzQT/7a7RIqFA==
|
||||
serverSecret: secret://zkConfig-libsignal-0.42.serverSecret
|
||||
|
||||
callingZkConfig:
|
||||
serverSecret: secret://callingZkConfig.serverSecret
|
||||
|
||||
backupsZkConfig:
|
||||
serverSecret: secret://backupsZkConfig.serverSecret
|
||||
chatZkConfig:
|
||||
serverSecret: secret://chatZkConfig.serverSecret
|
||||
|
||||
profileAvatarsZkConfig:
|
||||
serverSecret: secret://profileAvatarsZkConfig.serverSecret
|
||||
groupsZkConfig:
|
||||
serverPublic: AAp8oB0D4EV2q7hSue3Kxzh1Vc88/nmLuRR9G3EefC0+CMcxJFQwDMgjFvFBKx3o6m9gJLevYiKcm/NxXX9WtnFMDHgDgfqHxbCi2rm20SgoHnuoph6XArmEOX6a1xLJVxgDtgfm1IbcyyqROXYxe9v2RvMUAnjbLI/fm0rXXhldjszlVR/wRpybX90RUjFyL/2Achttf3IC/ShWKkB6mWXwuFCcNfzeCCQ+w7cNnDbWscBcrhuou7HZvbt16/YdCXLyp+WdwS8ZkelpITvyK2hsPvf4oxaRLQfVRYXUMX55xpapbKH6PthuOzMVRkf+I3Xz3/bNjiQSlQkmAXlgB1YujgABYnJ6yJXQKP2mR4UJ3UYoGroYoafWycDa+vUYYozaUmzFjsBYWpYE+HyPJlJ2QaFTrpVqxX7NXsSbg8t35IvfWfZME9YBZ2eErDunwkaE4iDQhHl5IXAhbHDrr2QaJ68YIkn7lJSgFDKGFB2kb6BvDUGzcpI/CTHQi6WlCqQidQLJWDFFdlYjrUCQM2vvJtgyGrSc89jdXTFjM31aqmtcPWgWL0qv+RmK/BC392Nsu8WoSJcAE4yhccQuRSemtolgwewnjasoOFBNOPh4+pX55SwhyTVgtwl+NTNVNFydxGp9Me8ogRWElzwA9BFtNAgQtlfgIyZRTetFqLkYmIBDxwMcpizDKES5lPhV2uJJuzcMq/06mVQz2OrXgglWk01uN8U59pfNFpTZhcGQv+MHjwEAudq5eLpt3aFrdxJ7D26Fwl5j215SJ0yZo7vmSEML1vf7FaGh0IL57bRpCvdebB5WapSChUX+PPvCXohVjGrERFvQpeET6pydGGlEKYLWuWa3zFGmPvJJYZ/QfcmIP9zyhqzQT/7a7RIqFA==
|
||||
serverSecret: secret://zkConfig-libsignal-0.42.serverSecret
|
||||
|
||||
dynamicConfig:
|
||||
type: static
|
||||
|
||||
Reference in new issue
Block a user